Sub topic 9
Avoiding Duplicate Results
This chapter assumes you already know the subset and permutation generators from earlier chapters, the path/used state they rely on, and how sorting a list works in Python.
Why duplicates appear
The plain subset generator treats every position in the input as its own element. If the input is [1, 2, 2], the two 2s sit at different indices, so the generator produces [1, 2] twice: once with the first 2 and once with the second. The output is still correct for positions. It is wrong for values, and most problems ask about values.
Removing duplicates afterwards with a set of tuples works, but the search still does all the wasted work first. A better fix never enters the duplicate branch at all.
The rule: one value per tree level
A level of the state-space tree is a single run of the for loop inside one call. Each iteration of that loop picks which element goes into the next slot. If two iterations at the same level pick the same value, they grow identical subtrees. So the rule is: at a given level, try each distinct value at most once.
To make this rule cheap, sort the input first. Equal values then sit next to each other, and "have I already tried this value at this level?" becomes "is this value equal to the one just before it in this loop?"
Subsets with duplicates
def subsets_with_dup(nums):
nums = sorted(nums)
result = []
path = []
def backtrack(start):
result.append(path[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue # skip a repeated value at the same tree level
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return result
print(subsets_with_dup([1, 2, 2]))
# [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]The condition i > start matters. The first iteration of each loop is always allowed, even when its value equals the element before it. That earlier element belongs to the parent level, so using the second 2 after the first 2 (giving [1, 2, 2]) is a new subset, not a duplicate.
Permutations with duplicates
Permutation loops always start at index 0, so i > start cannot tell you where a level begins. Use the used array instead. Of a group of equal values, only take the next one after its left neighbour is already in the path:
def permute_unique(nums):
nums = sorted(nums)
result = []
path = []
used = [False] * len(nums)
def backtrack():
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue # equal values are used left to right only
used[i] = True
path.append(nums[i])
backtrack()
path.pop()
used[i] = False
backtrack()
return result
print(permute_unique([1, 1, 2]))
# [[1, 1, 2], [1, 2, 1], [2, 1, 1]]Because equal values must be used left to right, each arrangement of values has exactly one ordering of indices that reaches it.
Common errors
| Mistake | Effect |
|---|---|
| Forgetting to sort | Equal values are not adjacent, so the neighbour check misses duplicates |
| Writing `i > 0` in the subset loop | Valid results such as `[1, 2, 2]` and `[2, 2]` are lost |
| Deduplicating the output with a set | The output is correct, but the search does all the wasted work first |
| Sorting `nums` but indexing the original list | The checks and the appended values disagree |
Exercise
In subsetswithdup([1, 2, 2]), suppose you change the check to i > 0 and nums[i] == nums[i - 1]. Which subsets disappear, and why?
Show answer
[1, 2, 2] and [2, 2] disappear. Both need the second 2 (index 2) as the first pick in a loop that starts at index 2. With i > 0, index 2 is always skipped because nums[2] == nums[1], even though index 1 was chosen at the parent level and not as a sibling in the same loop.
Exercise
How many results does permute_unique([2, 2, 2]) return, and how many complete paths reach the base case?
Show answer
It returns one result, [2, 2, 2]. Only one path reaches the base case, because the equal values must be used in index order 0, 1, 2. All other orderings are pruned before they finish.