Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Permutations
MEDIUM
10 mins
10 upvotes
Heap
Arrays
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Arrays
-
-
Heap
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
SQL
-
-
Binary Search Trees
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Permutations

Contributed by
Deep Mavani
Medium
yellow-spark
0/80
Avg time to solve 10 mins
Success Rate 90 %
Share
10 upvotes

Problem Statement

A permutation is a mathematical technique that determines the number of possible arrangements in a set when the order of the arrangements matters. A string of length 'N' has 'N'! permutations.

Given an array of distinct integers, return all the possible permutations of the array.

Example:
'ARR[]' = [1, 2]

The size of the array is 2. So, the total number of permutations is 2! = 2. The possible permutations are [1, 2] (the array itself) and [2,1] where the position of element 1 in the original array is swapped with element 2 and vice-versa.   
Note:
1. All the numbers in the array are unique.

2. You can return the answer in any order.

3. The original array is also a permutation of the given array.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample input 1:
2
3
1 2 3 
1
1
Sample Output 1:
1 2 3   1 3 2   2 1 3  2 3 1  3 1 2   3 2 1
1
Explanation of Sample Output 1:
In test case 1, For [1,2,3], size of the array is 3. Therefore, number of permutations is 3!= 6. The possible 6 permutations are [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]].

In test case 2, For [1], the size of the array is 1. Therefore, the number of permutations is 1!= 1. The only possible permutation is [1].
Sample input 2:
2
2
0 1
3
4 5 6
Sample output 2:
0 1  1 0
4 5 6   4 6 5   5 4 6   5 6 4   6 4 5   6 5 4
Explanation of Sample Output 2:
In test case 1, For [0, 1], size of the array is 2. Therefore, number of permutations is 2! = 2. The possible 2 permutations are [[0, 1], [1, 0]].

In test case 2, For [4, 5, 6], the size of the array is 3. Therefore, the number of permutations is 3! =  6. The possible 6 permutations are [[4, 5, 6], [4, 6, 5], [5, 4, 6], [5, 6, 4], [6, 4, 5], [6, 5, 4]].
Reset Code
Full screen
Auto
copy-code
Console