1

Permutations

Difficulty: EASY
Avg. time to solve
10 min
Success Rate
90%

Problem Statement
Suggest Edit

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.
4. Don’t print anything, just return the array of all the possible permutations.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘2*T’ lines represent the ‘T’ test cases.

The first line of each test case contains ‘n’ denoting the total number of elements in the array.
The second line of each test case contains ‘n’ space-separated integers denoting the elements of the array whose all possible permutations are to be calculated.
Output Format:
For each test case, return all the possible permutations of the given array of integers.
Constraints:
1 <= T <= 10
1 <= n <= 7
-10^9 <= arr[i] <= 10^9

Where ‘T’ is the total number of test cases, ‘n’ denotes the number of elements in the array, and ‘arr[i]’ denotes the range of elements in the array.

Time limit: 1 second
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 input 1
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]].

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
Reset Code
Full screen
copy-code
Console