Permutations - Problem

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

A permutation is a rearrangement of all elements in the array where each element appears exactly once in a different order.

Input & Output

Example 1 — Basic Three Elements
$ Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
💡 Note: All 6 possible arrangements of [1,2,3]: start with each element, then arrange the remaining two elements in all possible ways
Example 2 — Two Elements
$ Input: nums = [0,1]
Output: [[0,1],[1,0]]
💡 Note: Only 2 possible arrangements: [0,1] and [1,0]. With 2 elements, we have 2! = 2 permutations
Example 3 — Single Element
$ Input: nums = [1]
Output: [[1]]
💡 Note: With only one element, there's only one possible arrangement: [1]. 1! = 1 permutation

Constraints

  • 1 ≤ nums.length ≤ 6
  • -10 ≤ nums[i] ≤ 10
  • All the integers of nums are unique

Visualization

Tap to expand
Permutations - All Possible Arrangements INPUT Array of distinct integers 1 2 3 nums = [1, 2, 3] Decision Tree Start [ ] 1 2 3 Pick first element 3 choices available n = 3 elements Result: 3! = 6 perms ALGORITHM STEPS 1 Base Case Check If path.length == n, add permutation to result 2 Iterate Choices For each unused number, try adding to path 3 Recurse Deeper Mark num as used, call backtrack(path) 4 Backtrack Remove num from path, mark as unused again Backtracking Pattern [1] --> [1,2] --> OK undo [1,2] [1,3] try next FINAL RESULT All 6 permutations found: [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] Complete Decision Tree [ ] 1 2 3 2 perms 2 perms 2 perms Complexity Time: O(n * n!) Space: O(n) Key Insight: Backtracking builds permutations by trying each unused element at each position. When we reach a complete permutation (length = n), we save it. Then we "backtrack" by removing the last element and trying the next unused option. This explores all n! arrangements systematically without missing any combination. TutorialsPoint - Permutations | Backtracking Approach
Asked in
Amazon 45 Microsoft 38 Google 32 Apple 28
464.0K Views
High Frequency
~15 min Avg. Time
14.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen