Sub topic 9
Avoiding Duplicate Results
This chapter assumes you already know the choose-explore-unchoose template, how the subset and permutation generators work, and how the sorted break prunes combination-sum searches. All examples are in Python.
The generators from earlier chapters treat every input position as distinct. That is correct when the values are distinct. When the input contains repeated values, such as [1, 2, 2], the plain subset generator returns [1, 2] twice: once using the first 2 and once using the second. The results differ by position but are identical as values, and most problems want each distinct answer only once.
Why Duplicates Appear
Backtracking makes one choice per tree edge. If two sibling edges choose equal values, the subtrees below them are identical. Each one produces the same results, so every result in that subtree is emitted twice.
Duplicates therefore come from equal values chosen at the same level of the tree. Equal values chosen at different depths are fine. Taking the first 2 and then the second 2 is how you build [2, 2], a legitimate subset. The fix is to allow only one of a group of equal siblings to start a branch.
Rule One: Sort, Then Skip Equal Siblings
Sorting puts equal values next to each other. Inside the loop of one call, every iteration is a sibling edge, so you can skip any value equal to the one tried just before it in the same loop:
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 is i > start, not i > 0. When i == start, the element is the first sibling at this level, so it must be allowed even if it equals nums[i - 1]. In that case nums[i - 1] was chosen by the parent, one level up. With i > 0, the generator would never produce [2, 2], because the second 2 would always be skipped.
The same rule in combination sum
When each candidate may be used at most once and the candidates may repeat, combine the sibling skip with the sorted-input break:
def combination_sum2(candidates, target):
# Each candidate is used at most once; candidates may repeat.
candidates = sorted(candidates)
result = []
path = []
def backtrack(start, remaining):
if remaining == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
c = candidates[i]
if i > start and c == candidates[i - 1]:
continue # equal sibling: same subtree as the previous one
if c > remaining:
break # sorted: later candidates are too large too
path.append(c)
backtrack(i + 1, remaining - c)
path.pop()
backtrack(0, target)
return result
print(combination_sum2([10, 1, 2, 7, 6, 1, 5], 8))
# [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]The recursion passes i + 1 because each element is used at most once. That is how the two 1s can both appear in [1, 1, 6]: the second 1 is chosen one level deeper, where it is the first sibling.
Rule Two: Permutations Need a Different Test
Permutation generators have no start index. Every call loops over all positions and skips the ones already marked used. The siblings at one level are all the unused positions, so "the previous index" might belong to an element already placed higher up in the path.
The standard fix is to use the used array to tell the two cases apart. Among equal values, require that they are placed in index order. Copy i may be chosen only if copy i - 1 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 # an earlier equal copy is unused, so this is a duplicate sibling
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]]The logic works like this. If nums[i - 1] is equal and unused, then at this level the loop either already tried nums[i - 1] as a sibling, or will try it, so choosing nums[i] here would repeat that branch. If nums[i - 1] is used, it sits higher in the path, so nums[i] is the first available copy at this level and is allowed.
`not used[i - 1]` versus `used[i - 1]`
Some solutions write the condition as used[i - 1] instead. That version is also correct, because it forces equal copies to be placed in reverse index order. The two versions do differ in cost:
| Condition | Order forced on equal copies | Where wrong orders are cut | Relative cost |
|---|---|---|---|
| `not used[i - 1]` | Ascending index | At the level where the wrong copy is first chosen | Less work |
| `used[i - 1]` | Descending index | Often several levels deeper, after building a doomed prefix | More work |
| No condition plus a result set | None | Never; duplicates are filtered after being built | Most work |
Prefer not used[i - 1]. It prunes each bad branch as early as possible.
Alternative: Iterate Over Distinct Values
Sorting assumes the values can be compared. If they are hashable but not orderable, for example a mix of strings and tuples, count the values instead and branch over distinct keys. Each level then has exactly one edge per distinct value, so duplicate siblings cannot exist:
from collections import Counter
def permute_unique_counter(items):
counts = Counter(items)
result = []
path = []
def backtrack():
if len(path) == len(items):
result.append(path[:])
return
for value in counts:
if counts[value] == 0:
continue
counts[value] -= 1
path.append(value)
backtrack()
path.pop()
counts[value] += 1
backtrack()
return result
print(permute_unique_counter(['a', 'a', ('x', 1)]))
# [['a', 'a', ('x', 1)], ['a', ('x', 1), 'a'], [('x', 1), 'a', 'a']]Restoring the state means restoring the count. The rule is the same as restoring used[i] in the index-based version.
Why Not Just Deduplicate at the End?
You can always collect results into a set of tuples. This is correct and sometimes the quickest thing to write, but it has three costs:
- Time. The search still visits every duplicate subtree. For
[1, 1, 1, 1, 1, 1, 1, 1], the plain permutation generator builds 8! = 40,320 permutations to return one. - Memory. The set holds every distinct result. In-search skipping can stream results with no extra storage.
- Hashability and order. Results must be converted to tuples, and the set loses the generator's natural order.
Skipping inside the search prunes whole subtrees, so the work grows with the number of distinct answers, not the number of positional ones.
Common Errors
- Forgetting to sort. The skip compares neighbors only. In
[2, 1, 2]the two2s are not adjacent, so the duplicate survives. - Using
i > 0in start-based generators. This drops valid answers that repeat a value (see the warning above). - Passing
iinstead ofi + 1when elements are single-use. The search reuses the same element, which produces answers like[1, 1]from an input with only one1. - Sorting a copy but indexing the original. If you write
sorted_nums = sorted(nums)and then compare againstnums[i - 1], the check uses the unsorted order. - Placing the skip after the
breakin combination sum. This is harmless for correctness but easy to reorder wrongly. Keep the skip first so it reads as a statement about siblings.
Exercise
A student modifies subsetswithdup by changing the skip condition to if i > 0 and nums[i] == nums[i - 1]: continue. What does the function return for [2, 2], and why?
Show answer
It returns [[], [2]]. At the root, start = 0: i = 0 chooses the first 2, and i = 1 is skipped as intended. Inside the call for [2], start = 1 and i = 1, but the condition i > 0 is true and nums[1] == nums[0], so the second 2 is skipped there too. The subset [2, 2] is never built. The correct test, i > start, allows the first sibling at each level.
Exercise
How many results does permute_unique([1, 1, 2, 2]) return, and how many complete permutations would the plain permutation generator build for the same input?
Show answer
permute_unique returns 4! / (2! 2!) = 6 distinct permutations. The plain generator treats all four positions as distinct and builds 4! = 24 permutations, so each distinct arrangement appears 2! 2! = 4 times.
Exercise
In combination_sum2, the candidates are [1, 1, 1] and the target is 2. Trace which branches the root call tries, and state the final result.
Show answer
At the root (start = 0), i = 0 chooses 1 (remaining 1). In that call (start = 1), i = 1 chooses the second 1 and reaches remaining 0, recording [1, 1]. Then i = 2 is skipped because it equals candidates[1] and i > start. Back at the root, i = 1 and i = 2 are skipped as equal siblings of i = 0. The result is [[1, 1]].