MEDIUM NC#73 Backtracking
46. Permutations
📖 Problem
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
- •Recursive function frames
- •Push/pop state undo
- •Pruning branches early
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply Backtracking reasoning pattern
💡 Approach
- → Use backtracking to generate all permutations
- → Swap elements to explore different arrangements
- → When reaching end of array, save copy of current permutation
- → Time: O(n! * n), Space: O(n! * n) for results
🧭 Prerequisites
🛠️ Hints & Pitfalls
Hints
- •Use backtracking to generate all permutations
- •Swap elements to explore different arrangements
- •When reaching end of array, save copy of current permutation
Common Pitfalls
- •Time: O(n! * n), Space: O(n! * n) for results
🧪 Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
permute([1,2,3]); Expected:
[[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,2,1], [3,1,2]] Test Case 2
Not run Input:
permute([0,1]); Expected:
[[0,1], [1,0]] Test Case 3
Not run Input:
permute([1]); Expected:
[[1]] 📝 Code Editor
📤 Output