{"id":"subsets-ii","title":"Subsets II","difficulty":"medium","patterns":["backtracking"],"primaryConcept":"backtracking-subsets","concepts":["backtracking-subsets"],"problemForm":"core","companies":["Meta","Amazon","Microsoft"],"category":"backtracking","executionStyle":"solution-method","compareMode":"unordered-nested-array","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length","sizes":[4,5,6,7],"constraints":["duplicates","output-heavy"]},"description":"Given an integer array `nums` that may contain duplicates, return all possible unique subsets. The solution set must not contain duplicate subsets, and the subsets may be returned in any order.","examples":[{"input":"nums = [1,2,2]","output":"[[],[1],[1,2],[1,2,2],[2],[2,2]]","explanation":"The duplicate 2s produce only one [2] subset and one [1,2] subset."},{"input":"nums = [0]","output":"[[],[0]]","explanation":"A single element has two subsets."}],"constraints":[{"id":"1-len-nums-10","text":"1 <= len(nums) <= 10","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":10}},{"id":"10-nums-i-10","text":"-10 <= nums[i] <= 10","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-10,"max":10}},{"id":"the-solution-set-must-not-contain-duplicate-subsets","text":"The solution set must not contain duplicate subsets."}],"starterCode":"class Solution:\n    def subsetsWithDup(self, nums: list[int]) -> list[list[int]]:\n        # Your code here\n        pass","functionName":"subsetsWithDup","testCases":[{"id":"1","input":{"nums":[1,2,2]},"expected":[[],[1],[1,2],[1,2,2],[2],[2,2]],"description":"Canonical duplicate subset case."},{"id":"2","input":{"nums":[0]},"expected":[[],[0]],"description":"Single element."},{"id":"3","input":{"nums":[1,1]},"expected":[[],[1],[1,1]],"description":"Two equal values should not produce duplicate singleton subsets."},{"id":"4","input":{"nums":[-1,1,-1]},"expected":[[],[-1],[-1,-1],[-1,-1,1],[-1,1],[1]],"description":"Sorting groups duplicates even when the input is unsorted."},{"id":"h1","input":{"nums":[2,2,2]},"expected":[[],[2],[2,2],[2,2,2]],"description":"All values equal."},{"id":"h2","input":{"nums":[1,2,3]},"expected":[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]],"description":"Distinct values reduce to the standard subsets problem."},{"id":"h3","input":{"nums":[4,4,1,4]},"expected":[[],[1],[1,4],[1,4,4],[1,4,4,4],[4],[4,4],[4,4,4]],"description":"One distinct value plus a duplicate run."},{"id":"h4","input":{"nums":[1,1,2]},"expected":[[],[1],[1,1],[2],[1,2],[1,1,2]],"description":"Two copies of 1 still produce distinct subset choices."},{"id":"h5","input":{"nums":[0,0,1]},"expected":[[],[0],[0,0],[1],[0,1],[0,0,1]],"description":"Duplicate zeroes and a separate value."},{"id":"h6","input":{"nums":[1,1,2,2]},"expected":[[],[1],[1,1],[2],[1,2],[1,1,2],[2,2],[1,2,2],[1,1,2,2]],"description":"Two duplicate runs produce a compact subset lattice."},{"id":"topup-three-duplicate-groups","input":{"nums":[1,1,2,2]},"expected":[[],[1],[1,1],[1,1,2],[1,1,2,2],[1,2],[1,2,2],[2],[2,2]],"description":"Two duplicate groups create a compact Cartesian set of counts."},{"id":"topup-negative-duplicates","input":{"nums":[-1,-1,0,1]},"expected":[[],[-1],[-1,-1],[-1,-1,0],[-1,-1,0,1],[-1,-1,1],[-1,0],[-1,0,1],[-1,1],[0],[0,1],[1]],"description":"Negative duplicates and zero preserve unique subset generation."}],"hints":[{"level":1,"content":"Duplicate values only cause duplicate subsets when you start a branch with the same value more than once at the same depth.","revealPattern":false},{"level":2,"content":"Sort first so equal values are adjacent, then skip `nums[i]` when it equals `nums[i - 1]` and `i` is not the first choice at this depth.","revealPattern":true},{"level":3,"content":"Record the current path as a subset, then choose each next value, recurse, and pop it before trying the next choice.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"generate-and-deduplicate","name":"Generate all subsets, then deduplicate","summary":"Build every subset from every index and remove duplicates afterward.","decisionReason":"Equal values create identical subset branches: with [1, 2, 2], choosing the first 2 or the second 2 at the same depth produces the same subset. Deduplicating after generation stores copies the sorted skip rule can avoid before recursion.","complexity":{"time":"O(n * 2^n) plus deduplication overhead","space":"O(n * 2^n)"},"tradeoffs":["Runs in O(n * 2^n) plus deduplication overhead time and uses O(n * 2^n) space."],"isOptimal":false},{"id":"sorted-backtracking-skip","name":"Sorted backtracking with duplicate skips","summary":"Sort equal values together and skip duplicate branch starts at the same depth.","decisionReason":"Sorting puts equal nums next to each other, so each depth can skip a value when the previous equal value was not chosen for that sibling branch. The path state then visits each unique subset once.","complexity":{"time":"O(n * 2^n)","space":"O(n)"},"tradeoffs":["Runs in O(n * 2^n) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-result","title":"Create the result accumulator","description":"Initialize the list that will collect subset snapshots.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"initializes_result_accumulator","scope":"init-result","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Returning paths without collecting snapshots","Using a scalar counter instead of a result list"],"hint":"Every unique path snapshot is appended to this result.","semanticSpec":{"intent":"Initialize result accumulator state.","doneWhen":"A result collection exists before recursive exploration.","shouldFailWhen":"This step should fail if no result accumulator is initialized.","roles":["result accumulator"],"mustProve":["The solution initializes result accumulator state."],"mustNotAccept":["Only printing subsets."]}},{"id":"define-backtrack","title":"Define the recursive helper","description":"Create a helper that carries the start index and current subset path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"defines_recursive_helper","scope":"define-backtrack","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Using only nested loops with fixed depth","Forgetting the start index for future choices"],"hint":"The helper represents one node in the subset decision tree.","semanticSpec":{"intent":"Define recursive search helper.","doneWhen":"A recursive helper calls itself while carrying search state.","shouldFailWhen":"This step should fail if no recursive helper exists.","roles":["recursive helper","start index","current path"],"mustProve":["The solution defines a recursive helper."],"mustNotAccept":["A non-recursive fixed-depth shell."]}},{"id":"add-current-subset","title":"Record the current subset","description":"Append a copy of the current path as one valid subset.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"emits_solution_snapshot","scope":"add-current-subset","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Appending the live path object instead of a copy","Only recording subsets at the leaves"],"hint":"Every prefix path is itself a valid subset.","semanticSpec":{"intent":"Emit a snapshot of current search state.","doneWhen":"The current path is copied into the result accumulator.","shouldFailWhen":"This step should fail if no solution snapshot is emitted.","roles":["current path","result accumulator"],"mustProve":["The recursive search emits solution snapshots."],"mustNotAccept":["Appending the same mutable path reference."]}},{"id":"skip-duplicates","title":"Skip duplicate branch starts","description":"At the same recursion depth, skip a value when it equals the previous value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"skips_invalid_candidates","scope":"skip-used","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Skipping all duplicate values, including valid deeper copies","Forgetting the `i > start` depth check"],"hint":"Only skip a duplicate when it would start another branch at the same depth.","semanticSpec":{"intent":"Guard duplicate branch starts before choosing.","doneWhen":"A candidate guard skips duplicate choices at one recursion level.","shouldFailWhen":"This step should fail if duplicate candidates are never skipped.","roles":["choice index","previous value"],"mustProve":["The solution skips invalid candidates."],"mustNotAccept":["Generating duplicates and deduplicating only after the search."]}},{"id":"choose-explore-unchoose","title":"Choose, recurse, then undo","description":"Append a value to the path, recurse from the next index, then pop it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"choose_explore_unchoose","scope":"choose-explore-unchoose","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Forgetting to pop after recursion","Recursing without advancing the start index"],"hint":"The pop restores the path so the next sibling branch starts cleanly.","semanticSpec":{"intent":"Maintain rollback search state across recursive branches.","doneWhen":"The path is mutated, recursive exploration happens, and the mutation is rolled back.","shouldFailWhen":"This step should fail if choose or undo is missing.","roles":["current path","recursive call","rollback"],"mustProve":["The solution performs choose-explore-unchoose."],"mustNotAccept":["Mutation without rollback cleanup."]}},{"id":"initial-call","title":"Start the search","description":"Call the helper with start index 0 and an empty path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"kicks_off_recursive_search","scope":"initial-call","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Never calling the helper","Starting after the first element"],"hint":"The first call begins before any value has been chosen.","semanticSpec":{"intent":"Kick off recursive search from the initial state.","doneWhen":"The helper is called after definition with initial search state.","shouldFailWhen":"This step should fail if the recursive helper is never invoked.","roles":["initial call"],"mustProve":["The solution kicks off recursive search."],"mustNotAccept":["Defining a helper without calling it."]}},{"id":"return-result","title":"Return unique subsets","description":"Return the result accumulator after the search completes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"returns_solution_accumulator","scope":"return-result","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Returning the current path","Returning before recursive exploration finishes"],"hint":"The result accumulator contains every recorded subset snapshot.","semanticSpec":{"intent":"Return the completed solution accumulator.","doneWhen":"The function returns the result collection after recursion.","shouldFailWhen":"This step should fail if the result accumulator is not returned.","roles":["result accumulator","return value"],"mustProve":["The solution returns the solution accumulator."],"mustNotAccept":["Returning only the last path."]}}],"slides":[{"id":"the-task","chapter":"The obvious way","kind":"info","eyebrow":"Read the problem","title":"Return every unique subset","workspacePanel":"problem","body":["Return every distinct subset of nums, which may contain repeated values. A subset keeps some positions, drops the rest, and preserves the input order.","Different copies of the same value can create identical subsets through separate branches. The search must keep valid repeated values while skipping duplicate sibling choices."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-task-state","state":{"nums":[1,2,2],"stack":[],"labels":{"stack":"path"}}}]}},{"id":"naive-baseline","chapter":"The obvious way","kind":"code-trace","eyebrow":"Try the easy fix","title":"Generate all subsets, drop repeats with a set","workspacePanel":"trace","summary":"The reflex is to ignore duplicates while building, then clean up afterward: generate the full power set as if every value were distinct, and store each one in a set so repeats collapse. Watch what it builds for [1, 2, 2].","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def subsetsWithDup(nums: list[int]) -> list[list[int]]:\n    seen: set[tuple[int, ...]] = set()\n\n    def backtrack(start: int, path: list[int]) -> None:\n        seen.add(tuple(path))\n        for i in range(start, len(nums)):\n            path.append(nums[i])\n            backtrack(i + 1, path)\n            path.pop()\n\n    backtrack(0, [])\n    result: list[list[int]] = []\n    for subset in seen:\n        result.append(list(subset))\n    return result","steps":[{"id":"n0","title":"Record the empty path","codeLine":5,"summary":"The search starts at the root and stores (). One subset so far, and no duplicate work yet.","state":{"nums":[1,2,2],"stack":[],"labels":{"stack":"path"}}},{"id":"n1","title":"Choose the first 2 and store [2]","codeLine":5,"summary":"Down the branch that skips the 1 and takes the value at index 1, path is [2]. The set stores (2,).","state":{"nums":[1,2,2],"i":1,"stack":[2],"stackActive":[0],"labels":{"stack":"path"}}},{"id":"n2","title":"Choose the second 2 and store [2] again","codeLine":5,"summary":"A separate branch takes the value at index 2 instead. path is [2] once more, an identical subset the set quietly throws away.","state":{"nums":[1,2,2],"i":2,"stack":[2],"stackActive":[0],"labels":{"stack":"path"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const seen = new Map();\nfunction backtrack(start, path) {\n    seen.set(stableKey(Array.from(path)), Array.from(path));\n    for (let i = start; i < nums.length; i++) {\n        path.push(nums[i]);\n        backtrack((i + 1), path);\n        path.pop();\n    }\n}\nbacktrack(0, []);\nconst result = [];\nfor (const subset of seen.values()) {\n    result.push(Array.from(subset));\n}\nreturn result;","lineMap":{"2":1,"5":3,"6":4,"7":5,"8":6,"9":7,"11":10,"12":11,"13":12,"14":13,"15":15},"statementBundles":{"2":{"startLine":1,"endLine":2},"9":{"startLine":7,"endLine":9},"14":{"startLine":13,"endLine":14}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const seen: Map<string, Array<number>> = new Map();\nfunction backtrack(start: number, path: Array<number>): void {\n    seen.set(stableKey(Array.from(path)), Array.from(path));\n    for (let i = start; i < nums.length; i++) {\n        path.push(nums[i]);\n        backtrack((i + 1), path);\n        path.pop();\n    }\n}\nbacktrack(0, []);\nconst result: Array<Array<number>> = [];\nfor (const subset of seen.values()) {\n    result.push(Array.from(subset));\n}\nreturn result;","lineMap":{"2":1,"5":3,"6":4,"7":5,"8":6,"9":7,"11":10,"12":11,"13":12,"14":13,"15":15},"statementBundles":{"2":{"startLine":1,"endLine":2},"9":{"startLine":7,"endLine":9},"14":{"startLine":13,"endLine":14}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static void backtrack(int start, List<Integer> path, Set<List<Integer>> seen, List<Integer> nums) {\n    seen.add(new ArrayList<Integer>(path));\n    for (int i = ((Number)start).intValue(); i < nums.size(); i++) {\n        path.add(nums.get(i));\n        backtrack((i + 1), path, seen, nums);\n        path.remove(path.size() - 1);\n    }\n}\n\nSet<List<Integer>> seen = new HashSet<List<Integer>>();\nbacktrack(0, new ArrayList<>(), seen, nums);\nList<List<Integer>> result = new ArrayList<>();\nfor (List<Integer> subset : seen) {\n    result.add(new ArrayList<Integer>(subset));\n}\nreturn result;","lineMap":{"2":10,"5":2,"6":3,"7":4,"8":5,"9":6,"11":11,"12":12,"13":13,"14":14,"15":16},"statementBundles":{"9":{"startLine":6,"endLine":8},"14":{"startLine":14,"endLine":15}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"HashSet<List<int>> seen = new(StructuralSequenceComparer<int>());\nvoid Backtrack(int start, List<int> path) {\n    seen.Add(new List<int>(path));\n    for (int i = start; i < nums.Count; i++) {\n        path.Add(nums[i]);\n        Backtrack(i + 1, path);\n        path.RemoveAt(path.Count - 1);\n    }\n}\nBacktrack(0, new List<int>());\nList<List<int>> result = new();\nforeach (var subset in seen) {\n    result.Add(new List<int>(subset));\n}\nreturn result;","lineMap":{"2":1,"5":3,"6":4,"7":5,"8":6,"9":7,"11":10,"12":11,"13":12,"14":13,"15":15},"statementBundles":{"2":{"startLine":1,"endLine":2},"9":{"startLine":7,"endLine":9},"14":{"startLine":13,"endLine":14}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<void(int, vector<int>&)> backtrack;\n\nset<vector<int>> seen;\nbacktrack = [&]( int start, vector<int>& path ) -> void {\n    seen.insert(path);\n    for (int i = start; i < nums.size(); i++) {\n        path.push_back(nums[i]);\n        backtrack((i + 1), path);\n        path.pop_back();\n    }\n};\nvector<int> path = vector<int>{};\nbacktrack(0, path);\nvector<vector<int>> result;\nfor (vector<int> subset : seen) {\n    result.push_back(subset);\n}\nreturn result;","lineMap":{"2":3,"5":5,"6":6,"7":7,"8":8,"9":9,"11":12,"12":14,"13":15,"14":16,"15":18},"statementBundles":{"2":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":11},"11":{"startLine":12,"endLine":13},"14":{"startLine":16,"endLine":17}}}}}},{"id":"naive-cost","chapter":"Why it collapses","kind":"case-probe","eyebrow":"Count the waste","title":"How much work does the cleanup throw away?","workspacePanel":"trace","summary":"The trace showed [2] appear from two different branches. Now picture several equal copies of one value.","options":[{"id":"exponential","label":"It builds every branch the duplicates create, then discards the collisions","rationale":"Three equal values alone spawn branches for picking the 1st, the 2nd, the 3rd, the 1st-and-2nd, and so on, yet they collapse to just [2], [2, 2], [2, 2, 2]. The search walked all of them before the set merged them.","isCorrect":true},{"id":"constant","label":"Almost none, the set just costs a hash per subset","rationale":"The hashing is cheap, but the branches feeding it are not. The waste is in the duplicate subtrees the search fully explores before anything is deduplicated.","isCorrect":false},{"id":"sorting","label":"Only the final sort to order the output","rationale":"No sort is the bottleneck here. The cost is the repeated branches built and stored before the set ever collapses them.","isCorrect":false}],"answer":"It builds every duplicate branch in full, then discards the collisions, so the duplicates cost real work before they are merged away."},{"id":"trick-bridge","chapter":"The trick","kind":"info","eyebrow":"Change the plan","title":"Stop building the repeats at all","workspacePanel":"visualizer","body":["Cleaning up afterward still pays for every duplicate branch the search walks. The cheaper move is to never start a branch that can only rebuild a subset some sibling already produces.","To do that, we need to name exactly when two branches are doomed to collide. Look at the root of [1, 2, 2], where no value has been chosen yet, and ask which starts overlap."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"trick-bridge-state","state":{"nums":[1,2,2],"stack":[],"labels":{"stack":"path"}}}]}},{"id":"what-collides","chapter":"The trick","kind":"case-probe","eyebrow":"Find the rule","title":"What makes two branches build the same subset?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"what-collides-state","state":{"nums":[1,2,2],"i":2,"j":1,"stack":[],"labels":{"stack":"path","i":"this start","j":"sibling start"}}}]},"summary":"At the root, before anything is chosen, the loop is looking at index 1 and index 2. Both positions hold 2.","options":[{"id":"same-value-same-depth","label":"Two equal values are both used to start a branch at the same depth","rationale":"Starting at index 1 or index 2 here both begin with 2, and everything reachable after is identical, so the two branches produce exactly the same subsets. That is the only source of repeats.","isCorrect":true},{"id":"same-value-anywhere","label":"The same value is used twice anywhere in the search","rationale":"Using both 2s on one path gives [2, 2], a real subset. The repeat only happens when two equal values each start a branch at the same depth, not whenever a value reappears.","isCorrect":false},{"id":"deep-paths","label":"Only the longest paths, where every element is included","rationale":"The full set [1, 2, 2] is built once. The collisions are the short branches: two [2] starts, two [1, 2] starts.","isCorrect":false}],"answer":"Two equal values each starting a branch at the same depth, since everything after them is identical."},{"id":"the-rule","chapter":"The trick","kind":"case-probe","eyebrow":"Make it local","title":"How can one branch tell it is a repeat start?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-rule-state","state":{"nums":[1,2,2],"i":2,"j":1,"start":0,"stack":[],"stackActive":[],"labels":{"stack":"path","i":"i","j":"i - 1"}}}]},"summary":"At one recursion depth, the loop scans positions start, start+1, start+2 in a sorted array where equal values sit next to each other.","options":[{"id":"equals-previous","label":"Sort first, then skip a value when it equals its left neighbor and is not the first choice here","rationale":"Sorting puts equal values side by side, so a repeat start becomes exactly nums[i] == nums[i-1] with i past the first choice. The first copy starts the branch; every later equal copy at the same depth is skipped, no extra bookkeeping.","isCorrect":true},{"id":"value-in-path","label":"Its value already appears somewhere in the current path","rationale":"That would forbid [2, 2], which is a valid subset. The check is about siblings at one depth, not about reuse down a single branch.","isCorrect":false},{"id":"track-set","label":"Keep a set of values already tried and look each one up","rationale":"That works but rebuilds state you no longer need. After sorting, equal values are adjacent, so comparing to the immediate left neighbor is all the evidence required.","isCorrect":false}],"answer":"When nums[i] equals nums[i-1] and i is past the first choice at this depth, the left copy already started this branch, so skip."},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Walk the search","title":"Watch the skip fire on [1, 2, 2]","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"t0","state":{"nums":[1,2,2],"stack":[],"labels":{"stack":"path"}}},{"id":"t1","state":{"nums":[1,2,2],"i":2,"stack":[],"labels":{"stack":"path"}}},{"id":"t2","state":{"nums":[1,2,2],"i":2,"stack":[2],"stackActive":[0],"labels":{"stack":"path"}}}]},"beats":[{"id":"b-root","title":"At the root, which starts are open before any skip?","summary":"path is empty and the loop runs over indices 0, 1, 2 of [1, 2, 2].","options":[{"id":"one-and-first-two","label":"Start with the 1, or start with the first 2","rationale":"Index 0 (the 1) and index 1 (the first 2) each open a fresh branch. Index 2 is the second 2 and has not been judged yet.","isCorrect":true},{"id":"all-three","label":"All three positions start their own branch","rationale":"That is the bug the rule prevents. Index 2 holds a 2 equal to its left neighbor and is not the first choice here, so it must be skipped.","isCorrect":false},{"id":"only-one","label":"Only the 1, since the 2s are duplicates","rationale":"The first 2 is a legitimate start because it produces [2] and [2, 2]. Only the second 2 at this depth is the repeat.","isCorrect":false}],"answer":"The 1 and the first 2 each start a branch; the second 2 is still to be judged."},{"id":"b-skip","title":"The root loop advances to the second copy of 2. What happens?","summary":"The path is still empty, start is 0, and i has reached index 2, the second 2.","options":[{"id":"skip-it","label":"Skip it, because nums[2] equals nums[1] and i is not the first choice","rationale":"The first 2 already started the [2] branch here. Letting the second 2 start one too would rebuild [2] and [2, 2] identically, so it is skipped.","isCorrect":true},{"id":"take-it","label":"Take it and start a [2] branch","rationale":"That re-emits [2] and [2, 2] from the second copy. The skip exists precisely to stop this.","isCorrect":false},{"id":"stop","label":"Stop the loop entirely","rationale":"Skipping applies to this candidate only. Later distinct values at this depth would still deserve their own branch.","isCorrect":false}],"answer":"Skip it: nums[2] equals nums[1] and i is past the first choice, so the second 2 cannot start a branch here."},{"id":"b-deep","title":"Inside the first 2's branch, may the second 2 be chosen?","summary":"The first-2 branch recurses into the suffix after it: path is [2] and the loop now runs from index 2.","options":[{"id":"yes-deeper","label":"Yes, because at this depth the second 2 is the first choice","rationale":"start is now 2, so i equals start and the skip guard does not fire. Extending [2] with the second 2 gives [2, 2], a distinct subset that must be built.","isCorrect":true},{"id":"no-rule","label":"No, index 2 was skipped at the root, so it stays skipped here","rationale":"The guard is re-evaluated per call against the current start. At the root start was 0, so index 2 was a repeat sibling; here start is 2, so the same index is now the first choice.","isCorrect":false},{"id":"depends-prev","label":"Only if we first check that nums[2] differs from nums[1]","rationale":"That check would block it, but it is the wrong test for this depth. The guard uses both i and start: with start at index 2, i equals start, so the value match never matters.","isCorrect":false}],"answer":"Yes: with start at index 2 the second 2 is the first choice at this depth, so [2, 2] is built."}]},{"id":"skip-too-much","chapter":"Why it collapses","kind":"pitfall","eyebrow":"Spot the trap","title":"Could you just skip every repeated value?","workspacePanel":"trace","summary":"The skip looks like it should say: never choose a value equal to the one before it. Drop the i > start part and keep only nums[i] == nums[i-1]. It still kills the duplicate [2] branches, and the early subsets look right. Watch it reach for [2, 2].","pitfall":"The guard below skips a value whenever it equals its left neighbor, with no check for whether this is the first choice at the depth.","whyItMatters":"Dropping the i > start guard skips the second 2 even when it is the first choice at its own depth, so the branch that should extend [2] into [2, 2] never runs. [2, 2] and [1, 2, 2] vanish from the result. The guard must skip only repeat starts among siblings, written nums[i] == nums[i-1] and i > start.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def subsetsWithDup(nums: list[int]) -> list[list[int]]:\n    nums.sort()\n    result = []\n\n    def backtrack(start: int, path: list[int]) -> None:\n        result.append(path[:])\n        for i in range(start, len(nums)):\n            if i > 0 and nums[i] == nums[i - 1]:\n                continue\n            path.append(nums[i])\n            backtrack(i + 1, path)\n            path.pop()\n\n    backtrack(0, [])\n    return result","steps":[{"id":"p0","title":"Choose the first 2, record [2]","codeLine":6,"summary":"From the root the first 2 is the first choice, so it is allowed. path is [2] and [2] is recorded.","state":{"nums":[1,2,2],"i":1,"stack":[2],"stackActive":[0],"labels":{"stack":"path"}}},{"id":"p1","title":"Inside that branch, reach the second 2","codeLine":8,"summary":"Now start is index 2 and i is index 2. The guard only checks nums[i] == nums[i - 1], which is true, so it continues past the second 2.","state":{"nums":[1,2,2],"i":2,"stack":[2],"stackActive":[0],"labels":{"stack":"path"}}},{"id":"p2","title":"The branch ends with [2, 2] never built","codeLine":6,"summary":"With the second 2 skipped here, path can only stay [2]. [2, 2] is never recorded, and the full set [1, 2, 2] disappears too.","state":{"nums":[1,2,2],"stack":[2],"labels":{"stack":"path"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"nums.sort((a, b) => a - b);\nconst result = [];\nfunction backtrack(start, path) {\n    result.push(Array.from(path));\n    for (let i = start; i < nums.length; i++) {\n        if (i > 0 && nums[i] === nums[(i - 1)]) {\n            continue;\n        }\n        path.push(nums[i]);\n        backtrack((i + 1), path);\n        path.pop();\n    }\n}\nbacktrack(0, []);\nreturn result;","lineMap":{"2":1,"3":2,"6":4,"7":5,"8":6,"9":7,"10":9,"11":10,"12":11,"14":14,"15":15},"statementBundles":{"3":{"startLine":2,"endLine":3},"9":{"startLine":7,"endLine":8},"12":{"startLine":11,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"nums.sort((a, b) => a - b);\nconst result: Array<Array<number>> = [];\nfunction backtrack(start: number, path: Array<number>): void {\n    result.push(Array.from(path));\n    for (let i = start; i < nums.length; i++) {\n        if (i > 0 && nums[i] === nums[(i - 1)]) {\n            continue;\n        }\n        path.push(nums[i]);\n        backtrack((i + 1), path);\n        path.pop();\n    }\n}\nbacktrack(0, []);\nreturn result;","lineMap":{"2":1,"3":2,"6":4,"7":5,"8":6,"9":7,"10":9,"11":10,"12":11,"14":14,"15":15},"statementBundles":{"3":{"startLine":2,"endLine":3},"9":{"startLine":7,"endLine":8},"12":{"startLine":11,"endLine":13}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static void backtrack(int start, List<Integer> path, List<List<Integer>> result, List<Integer> nums) {\n    result.add(new ArrayList<Integer>(path));\n    for (int i = ((Number)start).intValue(); i < nums.size(); i++) {\n        if ((i > 0 && nums.get(i) == nums.get(i - 1))) {\n            continue;\n        }\n        path.add(nums.get(i));\n        backtrack((i + 1), path, result, nums);\n        path.remove(path.size() - 1);\n    }\n}\n\nCollections.sort(nums);\nList<List<Integer>> result = new ArrayList<>();\nbacktrack(0, new ArrayList<>(), result, nums);\nreturn result;","lineMap":{"2":13,"3":14,"6":2,"7":3,"8":4,"9":5,"10":7,"11":8,"12":9,"14":15,"15":16},"statementBundles":{"9":{"startLine":5,"endLine":6},"12":{"startLine":9,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"nums.Sort();\nList<List<int>> result = new();\nvoid Backtrack(int start, List<int> path) {\n    result.Add(new List<int>(path));\n    for (int i = start; i < nums.Count; i++) {\n        if (i > 0 && nums[i] == nums[i - 1]) {\n            continue;\n        }\n        path.Add(nums[i]);\n        Backtrack(i + 1, path);\n        path.RemoveAt(path.Count - 1);\n    }\n}\nBacktrack(0, new List<int>());\nreturn result;","lineMap":{"2":1,"3":2,"6":4,"7":5,"8":6,"9":7,"10":9,"11":10,"12":11,"14":14,"15":15},"statementBundles":{"3":{"startLine":2,"endLine":3},"9":{"startLine":7,"endLine":8},"12":{"startLine":11,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<void(int, vector<int>&)> backtrack;\n\nstable_sort(nums.begin(), nums.end());\nvector<vector<int>> result;\nbacktrack = [&]( int start, vector<int>& path ) -> void {\n    result.push_back(path);\n    for (int i = start; i < nums.size(); i++) {\n        if ((i > 0 && nums[i] == nums[(i - 1)])) {\n            continue;\n        }\n        path.push_back(nums[i]);\n        backtrack((i + 1), path);\n        path.pop_back();\n    }\n};\nvector<int> path = vector<int>{};\nbacktrack(0, path);\nreturn result;","lineMap":{"2":3,"3":4,"6":6,"7":7,"8":8,"9":9,"10":11,"11":12,"12":13,"14":16,"15":18},"statementBundles":{"3":{"startLine":4,"endLine":5},"9":{"startLine":9,"endLine":10},"12":{"startLine":13,"endLine":15},"14":{"startLine":16,"endLine":17}}}}}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Line it up","title":"Turn the rule into code","workspacePanel":"visualizer","ctaLabel":"Start coding","summary":"One subtlety carries the solution: skip a value only when it repeats its left neighbor and is not the first choice at this depth.","body":["Sort nums so equal values are adjacent, then start with an empty path and an empty result. The search records the current path on arrival and builds it deeper as it descends.","The high-level moves: record a copy of the path the moment you arrive, then loop from the start index. At each candidate, skip it when it equals its left neighbor and is past the first choice; otherwise choose it, recurse past it, and un-choose on the way back. When the search finishes, hand back result."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-state","state":{"nums":[1,2,2],"stack":[],"labels":{"stack":"path"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the unique-subset search","eyebrow":"Write it","summary":"Sort, set up the result, then choose-explore-unchoose down the tree, recording a copy on arrival and skipping a value when it equals its left neighbor and is past the first choice at this depth.","workspacePanel":"code","checkpoints":[{"id":"init-result","title":"Create the result accumulator","description":"Initialize the list that will collect subset snapshots.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"initializes_result_accumulator","scope":"init-result","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Returning paths without collecting snapshots","Using a scalar counter instead of a result list"],"hint":"Every unique path snapshot is appended to this result.","semanticSpec":{"intent":"Initialize result accumulator state.","doneWhen":"A result collection exists before recursive exploration.","shouldFailWhen":"This step should fail if no result accumulator is initialized.","roles":["result accumulator"],"mustProve":["The solution initializes result accumulator state."],"mustNotAccept":["Only printing subsets."]}},{"id":"define-backtrack","title":"Define the recursive helper","description":"Create a helper that carries the start index and current subset path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"defines_recursive_helper","scope":"define-backtrack","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Using only nested loops with fixed depth","Forgetting the start index for future choices"],"hint":"The helper represents one node in the subset decision tree.","semanticSpec":{"intent":"Define recursive search helper.","doneWhen":"A recursive helper calls itself while carrying search state.","shouldFailWhen":"This step should fail if no recursive helper exists.","roles":["recursive helper","start index","current path"],"mustProve":["The solution defines a recursive helper."],"mustNotAccept":["A non-recursive fixed-depth shell."]}},{"id":"add-current-subset","title":"Record the current subset","description":"Append a copy of the current path as one valid subset.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"emits_solution_snapshot","scope":"add-current-subset","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Appending the live path object instead of a copy","Only recording subsets at the leaves"],"hint":"Every prefix path is itself a valid subset.","semanticSpec":{"intent":"Emit a snapshot of current search state.","doneWhen":"The current path is copied into the result accumulator.","shouldFailWhen":"This step should fail if no solution snapshot is emitted.","roles":["current path","result accumulator"],"mustProve":["The recursive search emits solution snapshots."],"mustNotAccept":["Appending the same mutable path reference."]}},{"id":"skip-duplicates","title":"Skip duplicate branch starts","description":"At the same recursion depth, skip a value when it equals the previous value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"skips_invalid_candidates","scope":"skip-used","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Skipping all duplicate values, including valid deeper copies","Forgetting the `i > start` depth check"],"hint":"Only skip a duplicate when it would start another branch at the same depth.","semanticSpec":{"intent":"Guard duplicate branch starts before choosing.","doneWhen":"A candidate guard skips duplicate choices at one recursion level.","shouldFailWhen":"This step should fail if duplicate candidates are never skipped.","roles":["choice index","previous value"],"mustProve":["The solution skips invalid candidates."],"mustNotAccept":["Generating duplicates and deduplicating only after the search."]}},{"id":"choose-explore-unchoose","title":"Choose, recurse, then undo","description":"Append a value to the path, recurse from the next index, then pop it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"choose_explore_unchoose","scope":"choose-explore-unchoose","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Forgetting to pop after recursion","Recursing without advancing the start index"],"hint":"The pop restores the path so the next sibling branch starts cleanly.","semanticSpec":{"intent":"Maintain rollback search state across recursive branches.","doneWhen":"The path is mutated, recursive exploration happens, and the mutation is rolled back.","shouldFailWhen":"This step should fail if choose or undo is missing.","roles":["current path","recursive call","rollback"],"mustProve":["The solution performs choose-explore-unchoose."],"mustNotAccept":["Mutation without rollback cleanup."]}},{"id":"initial-call","title":"Start the search","description":"Call the helper with start index 0 and an empty path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"kicks_off_recursive_search","scope":"initial-call","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Never calling the helper","Starting after the first element"],"hint":"The first call begins before any value has been chosen.","semanticSpec":{"intent":"Kick off recursive search from the initial state.","doneWhen":"The helper is called after definition with initial search state.","shouldFailWhen":"This step should fail if the recursive helper is never invoked.","roles":["initial call"],"mustProve":["The solution kicks off recursive search."],"mustNotAccept":["Defining a helper without calling it."]}},{"id":"return-result","title":"Return unique subsets","description":"Return the result accumulator after the search completes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"returns_solution_accumulator","scope":"return-result","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Returning the current path","Returning before recursive exploration finishes"],"hint":"The result accumulator contains every recorded subset snapshot.","semanticSpec":{"intent":"Return the completed solution accumulator.","doneWhen":"The function returns the result collection after recursion.","shouldFailWhen":"This step should fail if the result accumulator is not returned.","roles":["result accumulator","return value"],"mustProve":["The solution returns the solution accumulator."],"mustNotAccept":["Returning only the last path."]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Carry it forward","summary":"You generated every unique subset without ever building a duplicate twice.","workspacePanel":"code","body":["Deduplicating after the fact pays for every repeat it later merges. Sorting plus a per-depth skip refuses to build the repeats in the first place, so the search only ever walks the distinct subsets."],"takeaways":[{"title":"Sort to make duplicates adjacent","body":"Equal values next to each other turn the repeat test into a comparison with the left neighbor, no extra bookkeeping needed."},{"title":"Skip repeat starts, not reuse","body":"nums[i] == nums[i-1] and i > start blocks a second equal value from starting a sibling branch, while still allowing a deeper copy to extend the path into [2, 2]."},{"title":"Prune beats clean-up","body":"Refusing to build a duplicate is cheaper than building it and discarding it, and it keeps the result free of repeats without a set."}],"nextAction":"Submit runs your code against every test, including the all-equal and unsorted-duplicate cases."}],"slidesOrigin":"authored"}}
