CodeArchon

mediumBacktrackingFacebookAmazon

Receipt Reconciler

A fraud auditor finds every subset of receipt amounts that reconciles to a disputed total — each receipt used at most once, duplicates in the pile must not inflate the answer list.

Given a possibly-duplicated candidate list and a target, return all unique combinations summing to target. Each element used at most once; no duplicate combinations.

Choose approach

10
0
j
1
1
2
2
7
3
6
4
1
5
5
6
SetCombos (0)
empty
1/21
Narrationstep 1 of 21

Sorted candidates, start DFS target=8.

1def combinationSum2(cands, target):
2 cands.sort()
3 out, cur = [], []
4 def dfs(i, remain):
5 if remain == 0:
6 out.append(cur[:]); return
7 for j in range(i, len(cands)):
8 if j > i and cands[j] == cands[j-1]: continue
9 if cands[j] > remain: break
10 cur.append(cands[j]); dfs(j+1, remain-cands[j]); cur.pop()
11 dfs(0, target); return out
Variables
remain=8
cur=[]
out=0

How to think about it

  1. Sort collapses duplicates to adjacent slots.
  2. `j > i && cands[j] == cands[j-1]` skips re-using the same value at the same depth.
  3. `j+1` recursion forbids reusing the same index.

Edge cases to catch in interview

  • All duplicates equal to target -> one combo per unique length.
  • No valid combo -> empty.

Examples

Example 1[[1,1,6],[1,2,5],[1,7],[2,6]]
{"values":[10,1,2,7,6,1,5],"target":8}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed