On this page
Permutations
TIP103 Unit 8 Session 2 (Click for link to problem statements)
Problem Highlights
- 🔗 Leetcode Link: Permutations
- 💡 Problem Difficulty: Medium
- ⏰ Time to complete: __ mins
- 🛠️ Topics: Array, Recursion, Backtracking
- 🗒️ Similar Questions: Next Permutation, Permutations II, Permutation Sequence
1: U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Be sure that you clarify the input and output parameters of the problem:
- What is a permutation?
- A permutation is nothing but an arrangement of given integers.
- What permutations are we returning in this problem?
- We return all possible arrangements of the given sequence.
- Can the input contain duplicate numbers?
- No. All the integers of nums are unique; Permutations II is the variant with duplicates.
Run through a set of example cases:
HAPPY CASE
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: nums = [0,1]
Output: [[0,1],[1,0]]
EDGE CASE
Input: nums = [1]
Output: [[1]]
2: M-atch
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
- Backtracking: choose a value for the next position, recurse to fill the rest, then undo the choice and try the next value. This is the approach implemented below.
- Loop through the array, in each iteration, a new number is added to different locations of results of previous iteration. Start from an empty List.
3: P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Build each permutation one position at a time with backtracking. At each step, try every value of nums that is not already in perm, append it, recurse to fill the remaining positions, and then pop it off before trying the next value. A list of N distinct values has N! permutations, and each one is a leaf of this recursion tree, reached after N choices. The E-valuate section below works out what the calls cost in total.
1. Start with an empty `perm` and a counter `n` of positions still to fill.
2. If `n` is 0, `perm` is a complete permutation: append a copy of it to `res` and return.
3. Otherwise, for each value in `nums` that is not already in `perm`:
a. Append the value to `perm`.
b. Recurse with `n - 1` to fill the remaining positions.
c. Pop the value off `perm` so the next value can take this position.
⚠️ Common Mistakes
- Appending
permitself toresinstead ofperm.copy(). Every entry would then refer to the same list object, whichperm.pop()empties again while backtracking, soreswould end up holding N! references to one empty list. - Forgetting to call
perm.pop()after the recursive call, so a value chosen in one branch is still inpermwhen the loop tries the next value. - Skipping used values with
nums[i] in permwhen the input can contain duplicates. That check only works because this problem guarantees distinct integers. With repeated values, track used indices instead. - Expecting the wrong number of results: N distinct values have exactly N! permutations (orderings, not combinations), so
[1, 2, 3]gives 3 x 2 x 1 = 6 lists.
4: I-mplement
Implement the code to solve the algorithm.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
n = len(nums)
def solve(n, perm):
if n==0:
res.append(perm.copy())
return None
for i in range(len(nums)):
# Skip values already used in perm. This works because the problem
# guarantees all integers in nums are unique; with duplicate inputs this
# check would wrongly skip repeated values (use a used-index array instead).
if nums[i] in perm: continue
# Choose: put nums[i] in the next position
perm.append(nums[i])
solve(n-1, perm)
# Un-choose: remove nums[i] so the next value can take this position
perm.pop()
solve(n, [])
return res
5: R-eview
Review the code by running specific example(s) and recording values (watchlist) of your code’s variables along the way.
- Trace through your code with an input to check for the expected output
- Catch possible edge cases and off-by-one errors
6: E-valuate
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
- Time Complexity: O(N^2 * N!) for the code above. A call where
permalready holdskvalues can only be reached by an ordering ofkdistinct values, so there are at most N! / (N - k)! such calls, and the total over everykis less than e * N!. Each call that has not finished a permutation loops over allNvalues ofnums, and eachnums[i] in permtest scans the listperm, which costs O(k). That is O(N * k) per call, and the calls withk = N - 1alone number N! and cost O(N^2) each, so the total is O(N^2 * N!). Each of the N! finished permutations is also copied withperm.copy()in O(N). Tracking used indices in a boolean array instead of searchingpermmakes each check O(1) and brings the total down to O(N * N!). - Space Complexity: O(N * N!) for the output, which holds N! permutations of length N each. Apart from the output,
permand the recursion stack use O(N).