Permutations II
LeetCode 47 · Medium · solution, intuition & step-by-step walkthrough
Backtrack over a frequency map, not over indices.
This is how I solved Permutations II (LeetCode 47), a medium problem from the Permutations pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
With duplicate values, choose from the distinct values that still have remaining copies instead of from positions. A frequency map makes each distinct choice appear once per level, so no duplicates are produced.
Approach
- 1
Counter of values.
- 2
Full length → record.
- 3
For each value with count > 0: use it (count−1), recurse, restore.
How I solved it
Backtracking on countsPythonO(n·n!) time
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
#maintain the frequency map, if used reduece, reset while backtrack
res=[]
def dfs(comb,cur_freq):
if len(comb)==len(nums):
res.append(comb[:])
return
for num in cur_freq:
if cur_freq[num]>0:
comb.append(num)
cur_freq[num]-=1
dfs(comb,cur_freq)
comb.pop()
cur_freq[num]+=1
dfs([],Counter(nums))
return res
Permutations II — FAQ
What is the intuition behind Permutations II?
With duplicate values, choose from the distinct values that still have remaining copies instead of from positions. A frequency map makes each distinct choice appear once per level, so no duplicates are produced.
How do you solve Permutations II (LeetCode 47)?
1. Counter of values. 2. Full length → record. 3. For each value with count > 0: use it (count−1), recurse, restore.
What is the time and space complexity of Permutations II?
Time: O(n · n!). Space: O(n). (Accepted approach: Backtracking on counts.)
What are common mistakes in Permutations II?
Iterating the Counter keys means each value is tried once per level.