{"id":"permutations-ii","title":"Permutations II","difficulty":"medium","patterns":["backtracking"],"primaryConcept":"backtracking-permutations","concepts":["backtracking-permutations"],"problemForm":"core","companies":["Amazon","Google","Meta"],"category":"backtracking","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length","sizes":[3,4,5],"constraints":["duplicates","output-heavy"]},"description":"Given an integer array `nums` that may contain duplicates, return all possible unique permutations in lexicographic order after sorting the input.","examples":[{"input":"nums = [1,1,2]","output":"[[1,1,2],[1,2,1],[2,1,1]]","explanation":"The two 1s are interchangeable, so only three unique arrangements exist."},{"input":"nums = [1,2,3]","output":"[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]","explanation":"All values are distinct, so there are 3! permutations."}],"constraints":[{"id":"1-len-nums-8","text":"1 <= len(nums) <= 8","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":8}},{"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-permutations","text":"The solution set must not contain duplicate permutations."}],"starterCode":"class Solution:\n    def permuteUnique(self, nums: list[int]) -> list[list[int]]:\n        # Your code here\n        pass","functionName":"permuteUnique","testCases":[{"id":"1","input":{"nums":[1,1,2]},"expected":[[1,1,2],[1,2,1],[2,1,1]],"description":"Canonical duplicate permutation case."},{"id":"2","input":{"nums":[1,2,3]},"expected":[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]],"description":"Distinct values produce all factorial permutations."},{"id":"3","input":{"nums":[0,0,1]},"expected":[[0,0,1],[0,1,0],[1,0,0]],"description":"Duplicate zeros are handled like any duplicate value."},{"id":"4","input":{"nums":[1,1,1]},"expected":[[1,1,1]],"description":"All values equal produces one permutation."},{"id":"h1","input":{"nums":[1,1,2,2]},"expected":[[1,1,2,2],[1,2,1,2],[1,2,2,1],[2,1,1,2],[2,1,2,1],[2,2,1,1]],"description":"Two duplicated values."},{"id":"h2","input":{"nums":[-1,1,-1]},"expected":[[-1,-1,1],[-1,1,-1],[1,-1,-1]],"description":"Negative duplicate values are sorted first."},{"id":"h3","input":{"nums":[1,2,2]},"expected":[[1,2,2],[2,1,2],[2,2,1]],"description":"A single duplicated value yields three unique orderings."},{"id":"h4","input":{"nums":[0,0,1,1]},"expected":[[0,0,1,1],[0,1,0,1],[0,1,1,0],[1,0,0,1],[1,0,1,0],[1,1,0,0]],"description":"Two duplicate groups create six unique permutations."},{"id":"h5","input":{"nums":[-1,-1,2]},"expected":[[-1,-1,2],[-1,2,-1],[2,-1,-1]],"description":"Negative duplicates still sort to the front."},{"id":"h6","input":{"nums":[1,1,1,2]},"expected":[[1,1,1,2],[1,1,2,1],[1,2,1,1],[2,1,1,1]],"description":"Three equal values collapse the permutation count sharply."},{"id":"h7","input":{"nums":[1,1,2,2,3]},"expected":[[1,1,2,2,3],[1,1,2,3,2],[1,1,3,2,2],[1,2,1,2,3],[1,2,1,3,2],[1,2,2,1,3],[1,2,2,3,1],[1,2,3,1,2],[1,2,3,2,1],[1,3,1,2,2],[1,3,2,1,2],[1,3,2,2,1],[2,1,1,2,3],[2,1,1,3,2],[2,1,2,1,3],[2,1,2,3,1],[2,1,3,1,2],[2,1,3,2,1],[2,2,1,1,3],[2,2,1,3,1],[2,2,3,1,1],[2,3,1,1,2],[2,3,1,2,1],[2,3,2,1,1],[3,1,1,2,2],[3,1,2,1,2],[3,1,2,2,1],[3,2,1,1,2],[3,2,1,2,1],[3,2,2,1,1]],"description":"Five values with two duplicate groups exercises the larger duplicate-pruning search tree."},{"id":"topup-five-with-triple-duplicate","input":{"nums":[2,2,2,1,1]},"expected":[[1,1,2,2,2],[1,2,1,2,2],[1,2,2,1,2],[1,2,2,2,1],[2,1,1,2,2],[2,1,2,1,2],[2,1,2,2,1],[2,2,1,1,2],[2,2,1,2,1],[2,2,2,1,1]],"description":"Five values with two duplicate groups exercise duplicate pruning."}],"hints":[{"level":1,"content":"A permutation path has length `len(nums)` when it is complete.","revealPattern":false},{"level":2,"content":"Track which indices are already used in the current path so each copy is used at most once.","revealPattern":true},{"level":3,"content":"After sorting, skip `nums[i]` when it equals `nums[i - 1]` and the previous copy has not been used in the current branch.","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-all-deduplicate","name":"Generate all permutations and deduplicate","summary":"Produce permutations treating equal values as different, then remove duplicate rows.","decisionReason":"With duplicates most of the n! rows are copies: [1,1,2] yields six paths for three distinct answers. Generating them all and then deduplicating pays full permutation cost for work the skip rule avoids before it happens.","complexity":{"time":"O(n! * n) plus deduplication overhead","space":"O(n! * n)"},"tradeoffs":["Runs in O(n! * n) plus deduplication overhead time and uses O(n! * n) space."],"isOptimal":false},{"id":"sorted-used-backtracking","name":"Sorted backtracking with used flags","summary":"Sort values, use index-level visited state, and skip duplicate sibling choices.","decisionReason":"Sorting puts equal values side by side, so one comparison against the previous index decides whether a choice would repeat a sibling's subtree. The search walks only distinct permutations, and the used flags are the only state it carries.","complexity":{"time":"O(U * n)","space":"O(n)"},"tradeoffs":["Runs in O(U * n) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-result","title":"Initialize result and used state","description":"Create the result accumulator and the used-index state for the current path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"initializes_result_accumulator","scope":"init-result","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Not storing completed permutations","Using values instead of indices for duplicate copies"],"hint":"The result collects snapshots, while used flags describe the current path.","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","used state"],"mustProve":["The solution initializes result accumulator state."],"mustNotAccept":["Only printing permutations."]}},{"id":"define-backtrack","title":"Define the recursive helper","description":"Create a helper that grows a permutation path recursively.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"defines_recursive_helper","scope":"define-backtrack","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Using fixed-depth loops","Forgetting to pass or close over the path state"],"hint":"The helper represents one partial permutation.","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","current path"],"mustProve":["The solution defines a recursive helper."],"mustNotAccept":["A non-recursive fixed-depth shell."]}},{"id":"base-case","title":"Emit complete paths","description":"When the path length equals the input length, append a copy and return.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"checks_completion_before_emit","scope":"base-case","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Emitting partial paths","Continuing to recurse after a complete path"],"hint":"A full permutation uses exactly every input position once.","semanticSpec":{"intent":"Check terminal solution state before emitting.","doneWhen":"The helper emits a snapshot only when the path is complete.","shouldFailWhen":"This step should fail if the completion branch is missing.","roles":["current path","result accumulator"],"mustProve":["The solution checks completion before emitting."],"mustNotAccept":["Appending incomplete paths."]}},{"id":"skip-used-and-duplicates","title":"Skip unavailable choices","description":"Skip indices already in the path and skip duplicate sibling branches.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"skips_invalid_candidates","scope":"skip-used","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Using the same index twice","Skipping duplicate copies even when the previous copy is already used in this branch"],"hint":"The duplicate check should block only repeated sibling choices.","semanticSpec":{"intent":"Skip invalid candidate choices.","doneWhen":"The helper has guards that skip unavailable candidates before choosing.","shouldFailWhen":"This step should fail if used or duplicate candidates are never skipped.","roles":["used state","choice index"],"mustProve":["The solution skips invalid candidates."],"mustNotAccept":["Generating duplicates and deduplicating after the search."]}},{"id":"choose-explore-unchoose","title":"Choose, recurse, then undo","description":"Mark an index used, append its value, recurse, then pop and unmark.","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 unmark `used[i]`","Popping before the recursive call"],"hint":"Both path and used state must be restored after each branch.","semanticSpec":{"intent":"Maintain rollback search state across recursive branches.","doneWhen":"The search state is mutated, recursion happens, and the mutation is rolled back.","shouldFailWhen":"This step should fail if choose or undo is missing.","roles":["used state","current path","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 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":["Defining the helper but never calling it","Starting with a pre-filled path"],"hint":"The first recursive state has no chosen values.","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 permutations","description":"Return the completed result accumulator.","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 recursion finishes"],"hint":"The result accumulator contains copied complete paths.","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","kind":"info","chapter":"The arrangements","eyebrow":"Read the problem","title":"Every unique arrangement","workspacePanel":"problem","body":["You get an integer array that may repeat values, and you return every distinct ordering of those values. Each ordering uses all the values exactly once.","Equal values at different indices can create the same ordering through separate branches. The search must use every copy while skipping choices that duplicate a sibling branch."]},{"id":"brute-force","kind":"code-trace","chapter":"The obvious way","eyebrow":"Try everything","title":"Permute every position, by index","workspacePanel":"trace","summary":"The first instinct: place values into the ordering one position at a time, picking any index not yet used, exactly the way you would permute distinct values.","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def permute(nums: list[int]) -> list[list[int]]:\n    result = []\n    n = len(nums)\n    used = [False] * n\n    path = []\n\n    def build() -> None:\n        if len(path) == n:\n            result.append(path[:])\n            return\n        for i in range(n):\n            if used[i]:\n                continue\n            used[i] = True\n            path.append(nums[i])\n            build()\n            path.pop()\n            used[i] = False\n\n    build()\n    return result","steps":[{"id":"pick-first-1","title":"Pick index 0, the first 1","codeLine":14,"summary":"From an empty ordering the loop takes index 0, placing a 1 in the first slot.","state":{"nums":[1,1,2],"stack":[1],"stackActive":[0],"labels":{"stack":"path"},"used":[0],"i":0}},{"id":"complete-via-0","title":"One ordering lands: [1, 1, 2]","codeLine":9,"summary":"Continuing from index 0, the second 1 and the 2 fill the ordering, and [1, 1, 2] is recorded.","state":{"nums":[1,1,2],"stack":[1,1,2],"stackActive":[2],"labels":{"stack":"path"},"used":[0,1,2],"i":2}},{"id":"pick-second-1","title":"Back at the start, pick index 1, the other 1","codeLine":14,"summary":"The loop advances to index 1, the second 1, and starts the first slot over with it.","state":{"nums":[1,1,2],"stack":[1],"stackActive":[0],"labels":{"stack":"path"},"used":[1],"i":1}},{"id":"complete-via-1","title":"And [1, 1, 2] lands a second time","codeLine":9,"summary":"Starting from the second 1 fills in the first 1 and the 2, producing the identical ordering [1, 1, 2] again.","state":{"nums":[1,1,2],"stack":[1,1,2],"stackActive":[2],"labels":{"stack":"path"},"used":[0,1,2],"i":2}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nconst n = nums.length;\nconst used = Array(n).fill(false);\nconst path = [];\nfunction build() {\n    if (path.length == n) {\n        result.push(Array.from(path));\n        return;\n    }\n    for (let i = 0; i < n; i++) {\n        if (used[i]) {\n            continue;\n        }\n        used[i] = true;\n        path.push(nums[i]);\n        build();\n        path.pop();\n        used[i] = false;\n    }\n}\nbuild();\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"8":6,"9":7,"10":8,"11":10,"12":11,"13":12,"14":14,"15":15,"16":16,"17":17,"18":18,"20":21,"21":22},"statementBundles":{"5":{"startLine":4,"endLine":5},"10":{"startLine":8,"endLine":9},"13":{"startLine":12,"endLine":13},"18":{"startLine":18,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<Array<number>> = [];\nconst n = nums.length;\nconst used = Array(n).fill(false);\nconst path: Array<number> = [];\nfunction build(): void {\n    if (path.length == n) {\n        result.push(Array.from(path));\n        return;\n    }\n    for (let i = 0; i < n; i++) {\n        if (used[i]) {\n            continue;\n        }\n        used[i] = true;\n        path.push(nums[i]);\n        build();\n        path.pop();\n        used[i] = false;\n    }\n}\nbuild();\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"8":6,"9":7,"10":8,"11":10,"12":11,"13":12,"14":14,"15":15,"16":16,"17":17,"18":18,"20":21,"21":22},"statementBundles":{"5":{"startLine":4,"endLine":5},"10":{"startLine":8,"endLine":9},"13":{"startLine":12,"endLine":13},"18":{"startLine":18,"endLine":20}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> result = new();\nint n = nums.Count;\nList<bool> used = Enumerable.Repeat<bool>(false, n).ToList();\nList<int> path = new();\nvoid Build() {\n    if (path.Count == n) {\n        result.Add(new List<int>(path));\n        return;\n    }\n    for (int i = 0; i < n; i++) {\n        if (used[i]) {\n            continue;\n        }\n        used[i] = true;\n        path.Add(nums[i]);\n        Build();\n        path.RemoveAt(path.Count - 1);\n        used[i] = false;\n    }\n}\nBuild();\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"8":6,"9":7,"10":8,"11":10,"12":11,"13":12,"14":14,"15":15,"16":16,"17":17,"18":18,"20":21,"21":22},"statementBundles":{"5":{"startLine":4,"endLine":5},"10":{"startLine":8,"endLine":9},"13":{"startLine":12,"endLine":13},"18":{"startLine":18,"endLine":20}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<void()> build;\n\nvector<vector<int>> result;\nint n = nums.size();\nvector<bool> used = vector<bool>(n, false);\nvector<int> path;\nbuild = [&](  ) -> void {\n    if (path.size() == n) {\n        result.push_back(path);\n        return;\n    }\n    for (int i = 0; i < n; i++) {\n        if (used[i]) {\n            continue;\n        }\n        used[i] = true;\n        path.push_back(nums[i]);\n        build();\n        path.pop_back();\n        used[i] = false;\n    }\n};\nbuild();\nreturn result;","lineMap":{"2":3,"3":4,"4":5,"5":6,"8":8,"9":9,"10":10,"11":12,"12":13,"13":14,"14":16,"15":17,"16":18,"17":19,"18":20,"20":23,"21":24},"statementBundles":{"5":{"startLine":6,"endLine":7},"10":{"startLine":10,"endLine":11},"13":{"startLine":14,"endLine":15},"18":{"startLine":20,"endLine":22}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static void build(Deque<Integer> path, int n, List<List<Integer>> result, List<Boolean> used, List<Integer> nums) {\n    if (path.size() == n) {\n        result.add(new ArrayList<Integer>((Collection<Integer>)(Collection<?>)path));\n        return;\n    }\n    for (int i = 0; i < n; i++) {\n        if (used.get(i)) {\n            continue;\n        }\n        used.set(i, true);\n        path.addLast(nums.get(i));\n        build(path, n, result, used, nums);\n        path.pollLast();\n        used.set(i, false);\n    }\n}\n\nList<List<Integer>> result = new ArrayList<>();\nint n = nums.size();\nList<Boolean> used = new ArrayList<>();\nfor (int index = 0; index < n; index++) {\n    used.add(false);\n}\nDeque<Integer> path = new ArrayDeque<>();\nbuild(path, n, result, used, nums);\nreturn result;","lineMap":{"2":18,"3":19,"4":20,"5":24,"8":2,"9":3,"10":4,"11":6,"12":7,"13":8,"14":10,"15":11,"16":12,"17":13,"18":14,"20":25,"21":26},"statementBundles":{"4":{"startLine":20,"endLine":23},"10":{"startLine":4,"endLine":5},"13":{"startLine":8,"endLine":9},"18":{"startLine":14,"endLine":16}}}}}},{"id":"brute-force-cost","kind":"case-probe","chapter":"The obvious way","eyebrow":"Count the waste","title":"How many orderings does this record for [1, 1, 2], and how many are distinct?","workspacePanel":"trace","summary":"Treating the two 1s as different positions, every index permutation is built.","options":[{"id":"six-three","label":"Six recorded, but only three distinct","rationale":"Indices give 3! = 6 orderings, but swapping the two equal 1s produces the same values, so each of the 3 real arrangements is recorded twice.","isCorrect":true},{"id":"three-three","label":"Three recorded, all distinct","rationale":"Nothing here notices that the two 1s are equal, so it records all 6 index orderings even though only 3 value orderings are distinct."},{"id":"six-six","label":"Six recorded, all distinct","rationale":"The first 1 and the second 1 hold the same value, so the six index orderings collapse to three distinct value orderings."}],"answer":"Six recorded, three distinct. The two equal 1s sit in either order for the same arrangement, so every real ordering is built twice, and the duplication grows with each repeated value."},{"id":"skip-duplicate-sibling","kind":"case-probe","chapter":"The idea","eyebrow":"Find the cut","title":"With nums sorted so equal values are adjacent, which choice of the second 1 repeats a whole subtree?","workspacePanel":"visualizer","summary":"At the first slot, nums = [1, 1, 2] and used = [false, false, false].","options":[{"id":"prev-unused","label":"Picking the second 1 while the first 1 is still unplaced","rationale":"If the earlier equal value has not been placed yet, starting with the later copy walks the exact same arrangements the earlier copy already covers, so that branch is pure repetition.","isCorrect":true},{"id":"prev-used","label":"Picking the second 1 right after the first 1 was placed","rationale":"Once the first 1 is in the ordering, the second 1 is a genuinely new position deeper in the branch, like the [1, 1, ...] arrangements, so that choice is needed, not skipped."},{"id":"any-equal","label":"Picking either 1 at all, since they are equal","rationale":"One of the equal copies must lead each arrangement; skipping both would drop every ordering that starts with a 1. Only the redundant later copy is cut."}],"answer":"Picking the second 1 while the first 1 is still unplaced. That sibling branch re-walks what the first copy already covers, so cutting it at each level keeps exactly one ordering per arrangement.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dup-sibling-state","state":{"nums":[1,1,2],"stack":[],"stackActive":[],"labels":{"stack":"path"},"used":[],"i":1}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which approach should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"nums":[1,1,2],"stack":[],"stackActive":[],"labels":{"stack":"path"},"used":[]}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Choose, recurse, undo, and skip repeats","workspacePanel":"visualizer","body":["The path holds the ordering built so far, and a used flag per position marks which copies are already placed. Sorting puts the two 1s next to each other so the repeat check can compare neighbors.","Tracing nums = [1, 1, 2], we will place the first 1 in the opening slot, then reach the other 1 as the next candidate for that same slot and decide what to do with it."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"nums":[1,1,2],"stack":[],"stackActive":[],"labels":{"stack":"path"},"used":[],"i":0}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Build an ordering","title":"Build one ordering and inspect the next duplicate choice","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"choose-first","state":{"nums":[1,1,2],"stack":[1],"stackActive":[0],"labels":{"stack":"path"},"used":[0],"i":0}},{"id":"refuse-second","state":{"nums":[1,1,2],"stack":[],"stackActive":[],"labels":{"stack":"path"},"used":[],"i":1}},{"id":"emit","state":{"nums":[1,1,2],"stack":[1,1,2],"stackActive":[2],"labels":{"stack":"path"},"used":[0,1,2],"i":2}}]},"beats":[{"id":"choose-first","title":"The first slot takes index 0. What is placed?","summary":"The ordering starts empty and the loop is at index 0.","prompt":"nums = [1, 1, 2], and index 0 is unplaced.","options":[{"id":"one","label":"A 1, and index 0 is marked placed","rationale":"Index 0 holds a 1, so the path becomes [1] and used[0] turns true for the rest of this branch.","isCorrect":true},{"id":"two","label":"A 2, the largest value","rationale":"The loop runs in index order from 0, and index 0 holds a 1."},{"id":"nothing","label":"Nothing, the duplicate check skips it","rationale":"Index 0 is the earliest copy of the 1, so the repeat check never fires here; it is placed."}],"answer":"A 1. Index 0 is placed, the path becomes [1], and used[0] is now true."},{"id":"refuse-second","title":"Back at the first slot, index 1 is the other 1. Place it or refuse it?","summary":"The path is empty again at the root, and the first 1 was already explored from here.","prompt":"At this slot used = [false, false, false], and index 1 equals index 0 in value.","options":[{"id":"refuse","label":"Refuse it, the earlier equal 1 is unplaced","rationale":"Index 1 equals index 0 and index 0 is not placed in this branch, so leading with the second 1 would repeat the first 1's arrangements; the branch is cut.","isCorrect":true},{"id":"place","label":"Place it, it is a different position","rationale":"It is a different index but the same value, and its twin is still unplaced, so starting with it only re-walks orderings already produced."},{"id":"place-deeper","label":"Place it, and refuse it only deeper down","rationale":"The refusal is exactly here at the root level where both 1s are unplaced; deeper down, once the first 1 is placed, the second 1 is allowed."}],"answer":"Refuse it. The earlier 1 is still unplaced, so leading with the second 1 repeats a subtree; the branch is skipped at this slot."},{"id":"emit","title":"Down the kept branch the path reaches [1, 1, 2]. What now?","summary":"Every position is placed.","prompt":"path = [1, 1, 2] and used = [true, true, true].","options":[{"id":"record","label":"Record a copy of [1, 1, 2], then backtrack","rationale":"The path length matches the input, so a snapshot is stored before the pops mutate the path for sibling branches.","isCorrect":true},{"id":"continue","label":"Keep recursing for more values","rationale":"Every position is placed, so there is nothing left to choose; the branch records and unwinds."},{"id":"store-ref","label":"Store the path itself and move on","rationale":"Storing the live path lets later pops corrupt the recorded ordering; a copy must be taken at this moment."}],"answer":"Record a copy of [1, 1, 2], then backtrack. The ordering is complete, so a snapshot is saved before the path is unwound."}]},{"id":"missing-guard-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Does the neighbor check need the unplaced clause?","workspacePanel":"trace","summary":"The neighbor check is in place: skip nums[i] when it equals nums[i-1]. But it drops the and not used[i-1] clause, so it refuses a duplicate even when its twin is already placed. Watch what that does to [1, 1, 2].","pitfall":"The duplicate guard reads if i > 0 and nums[i] == nums[i - 1]: continue, with no check on whether the earlier copy is already in the path.","whyItMatters":"The clause and not used[i-1] is what makes the guard prune only sibling repeats. Without it, the second 1 is refused everywhere, including deeper in the branch where the first 1 is already placed and the second 1 is a genuinely new position. So the path can never reach [1, 1, ...], and every ordering that uses both 1s next to each other is lost. On [1, 1, 2] the search returns nothing at all. Restoring and not used[i-1] refuses the second 1 only while its twin is unplaced, so the duplicate sibling is cut but the deeper placement is allowed.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def permute(nums: list[int]) -> list[list[int]]:\n    nums.sort()\n    result = []\n    n = len(nums)\n    used = [False] * n\n    path = []\n\n    def build() -> None:\n        if len(path) == n:\n            result.append(path[:])\n            return\n        for i in range(n):\n            if used[i]:\n                continue\n            if i > 0 and nums[i] == nums[i - 1]:\n                continue\n            used[i] = True\n            path.append(nums[i])\n            build()\n            path.pop()\n            used[i] = False\n\n    build()\n    return result","steps":[{"id":"place-first-1","title":"The first 1 leads, and the path holds [1]","codeLine":18,"summary":"Index 0 is the earliest copy, so the guard does not fire; the first 1 is placed and the branch recurses.","state":{"nums":[1,1,2],"stack":[1],"stackActive":[0],"labels":{"stack":"path"},"used":[0],"i":0}},{"id":"wrong-refuse-second-1","title":"Deeper in, the second 1 is refused even though its twin is placed","codeLine":15,"summary":"used[0] is already true, so the second 1 is a genuinely new position here, but the guard skips it anyway because it only compares values.","state":{"nums":[1,1,2],"stack":[1],"stackActive":[0],"labels":{"stack":"path"},"used":[0],"i":1}},{"id":"ordering-lost","title":"The path can never reach [1, 1, ...], so nothing is recorded","codeLine":10,"summary":"With the second 1 unreachable behind the first, [1, 1, 2] and [1, 2, 1] both die; the search returns an empty result.","state":{"nums":[1,1,2],"stack":[1,2],"stackActive":[1],"labels":{"stack":"path"},"used":[0,2],"i":1}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"nums.sort((a, b) => a - b);\nconst result = [];\nconst n = nums.length;\nconst used = Array(n).fill(false);\nconst path = [];\nfunction build() {\n    if (path.length == n) {\n        result.push(Array.from(path));\n        return;\n    }\n    for (let i = 0; i < n; i++) {\n        if (used[i]) {\n            continue;\n        }\n        if (i > 0 && nums[i] === nums[(i - 1)]) {\n            continue;\n        }\n        used[i] = true;\n        path.push(nums[i]);\n        build();\n        path.pop();\n        used[i] = false;\n    }\n}\nbuild();\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"9":7,"10":8,"11":9,"12":11,"13":12,"14":13,"15":15,"16":16,"17":18,"18":19,"19":20,"20":21,"21":22,"23":25,"24":26},"statementBundles":{"6":{"startLine":5,"endLine":6},"11":{"startLine":9,"endLine":10},"14":{"startLine":13,"endLine":14},"16":{"startLine":16,"endLine":17},"21":{"startLine":22,"endLine":24}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"nums.sort((a, b) => a - b);\nconst result: Array<Array<number>> = [];\nconst n = nums.length;\nconst used = Array(n).fill(false);\nconst path: Array<number> = [];\nfunction build(): void {\n    if (path.length == n) {\n        result.push(Array.from(path));\n        return;\n    }\n    for (let i = 0; i < n; i++) {\n        if (used[i]) {\n            continue;\n        }\n        if (i > 0 && nums[i] === nums[(i - 1)]) {\n            continue;\n        }\n        used[i] = true;\n        path.push(nums[i]);\n        build();\n        path.pop();\n        used[i] = false;\n    }\n}\nbuild();\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"9":7,"10":8,"11":9,"12":11,"13":12,"14":13,"15":15,"16":16,"17":18,"18":19,"19":20,"20":21,"21":22,"23":25,"24":26},"statementBundles":{"6":{"startLine":5,"endLine":6},"11":{"startLine":9,"endLine":10},"14":{"startLine":13,"endLine":14},"16":{"startLine":16,"endLine":17},"21":{"startLine":22,"endLine":24}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"nums.Sort();\nList<List<int>> result = new();\nint n = nums.Count;\nList<bool> used = Enumerable.Repeat<bool>(false, n).ToList();\nList<int> path = new();\nvoid Build() {\n    if (path.Count == n) {\n        result.Add(new List<int>(path));\n        return;\n    }\n    for (int i = 0; i < n; i++) {\n        if (used[i]) {\n            continue;\n        }\n        if (i > 0 && nums[i] == nums[i - 1]) {\n            continue;\n        }\n        used[i] = true;\n        path.Add(nums[i]);\n        Build();\n        path.RemoveAt(path.Count - 1);\n        used[i] = false;\n    }\n}\nBuild();\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"9":7,"10":8,"11":9,"12":11,"13":12,"14":13,"15":15,"16":16,"17":18,"18":19,"19":20,"20":21,"21":22,"23":25,"24":26},"statementBundles":{"6":{"startLine":5,"endLine":6},"11":{"startLine":9,"endLine":10},"14":{"startLine":13,"endLine":14},"16":{"startLine":16,"endLine":17},"21":{"startLine":22,"endLine":24}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<void()> build;\n\nstable_sort(nums.begin(), nums.end());\nvector<vector<int>> result;\nint n = nums.size();\nvector<bool> used = vector<bool>(n, false);\nvector<int> path;\nbuild = [&](  ) -> void {\n    if (path.size() == n) {\n        result.push_back(path);\n        return;\n    }\n    for (int i = 0; i < n; i++) {\n        if (used[i]) {\n            continue;\n        }\n        if ((i > 0 && nums[i] == nums[(i - 1)])) {\n            continue;\n        }\n        used[i] = true;\n        path.push_back(nums[i]);\n        build();\n        path.pop_back();\n        used[i] = false;\n    }\n};\nbuild();\nreturn result;","lineMap":{"2":3,"3":4,"4":5,"5":6,"6":7,"9":9,"10":10,"11":11,"12":13,"13":14,"14":15,"15":17,"16":18,"17":20,"18":21,"19":22,"20":23,"21":24,"23":27,"24":28},"statementBundles":{"6":{"startLine":7,"endLine":8},"11":{"startLine":11,"endLine":12},"14":{"startLine":15,"endLine":16},"16":{"startLine":18,"endLine":19},"21":{"startLine":24,"endLine":26}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static void build(Deque<Integer> path, int n, List<List<Integer>> result, List<Boolean> used, List<Integer> nums) {\n    if (path.size() == n) {\n        result.add(new ArrayList<Integer>((Collection<Integer>)(Collection<?>)path));\n        return;\n    }\n    for (int i = 0; i < n; i++) {\n        if (used.get(i)) {\n            continue;\n        }\n        if ((i > 0 && nums.get(i) == nums.get(i - 1))) {\n            continue;\n        }\n        used.set(i, true);\n        path.addLast(nums.get(i));\n        build(path, n, result, used, nums);\n        path.pollLast();\n        used.set(i, false);\n    }\n}\n\nCollections.sort(nums);\nList<List<Integer>> result = new ArrayList<>();\nint n = nums.size();\nList<Boolean> used = new ArrayList<>();\nfor (int index = 0; index < n; index++) {\n    used.add(false);\n}\nDeque<Integer> path = new ArrayDeque<>();\nbuild(path, n, result, used, nums);\nreturn result;","lineMap":{"2":21,"3":22,"4":23,"5":24,"6":28,"9":2,"10":3,"11":4,"12":6,"13":7,"14":8,"15":10,"16":11,"17":13,"18":14,"19":15,"20":16,"21":17,"23":29,"24":30},"statementBundles":{"5":{"startLine":24,"endLine":27},"11":{"startLine":4,"endLine":5},"14":{"startLine":8,"endLine":9},"16":{"startLine":11,"endLine":12},"21":{"startLine":17,"endLine":19}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs lean on the repeat check?","workspacePanel":"visualizer","body":["Sorting equal values together and refusing a later copy while its twin is unplaced gave exactly one ordering per arrangement.","Now push on that rule with two inputs: first one where every value is equal, then one with two separate groups of duplicates."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"nums":[1,1,1],"stack":[],"stackActive":[],"labels":{"stack":"path"},"used":[]}}]}},{"id":"all-equal-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"How many orderings come out when every value is identical?","workspacePanel":"visualizer","summary":"nums = [1, 1, 1].","options":[{"id":"one","label":"One, just [1, 1, 1]","rationale":"At every slot, each later 1 has an unplaced equal twin before it, so only the earliest unplaced 1 is ever chosen, leaving a single ordering.","isCorrect":true},{"id":"six","label":"Six, since three positions can be ordered 3! ways","rationale":"Those six index orderings are exactly the duplicates the repeat check removes; all three values are equal, so only one distinct ordering survives."},{"id":"three","label":"Three, one led by each position","rationale":"Leading with a later 1 is refused while its twin is unplaced, so the three positions do not each yield an ordering; only one remains."}],"answer":"One. With every value equal, the repeat check refuses every later copy at each slot, so [1, 1, 1] is built exactly once.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-equal-state","state":{"nums":[1,1,1],"stack":[],"stackActive":[],"used":[],"i":1,"labels":{"stack":"path"}}}]}},{"id":"two-groups-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"Two values each repeat. Does one repeat check cover both?","workspacePanel":"visualizer","summary":"nums = [1, 1, 2, 2].","options":[{"id":"each-level","label":"Yes, because the check runs at every slot, not on one value","rationale":"The check compares each candidate to its sorted neighbor at every level, so the second 1 and the second 2 are both refused while their twins are unplaced, in whichever slot they appear.","isCorrect":true},{"id":"first-only","label":"No, it only dedupes the first repeated value it meets","rationale":"The check is not tied to one value; it fires for any candidate equal to its unplaced neighbor, so both the 1s and the 2s are handled."},{"id":"sort-fixes","label":"No repeat check is needed once the array is sorted","rationale":"Sorting only makes equal values adjacent; without the neighbor check the second 1 and second 2 still lead duplicate subtrees."}],"answer":"Yes. The neighbor comparison runs at every slot, so both repeated groups are pruned wherever a later copy would lead a subtree its twin already covers.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-groups-state","state":{"nums":[1,1,2,2],"stack":[1],"stackActive":[0],"used":[0],"i":1,"labels":{"stack":"path"}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"Sorting plus one neighbor check is the whole difference from plain permutations.","body":["Sort first so equal values sit together, then build orderings the usual way: place an unplaced position, recurse, and undo it before trying the next.","Before placing a position, refuse it when its value equals the previous position's and that earlier copy is still unplaced in this branch. Record a copy of the ordering once every position is placed."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[1,1,2],"stack":[],"stackActive":[],"labels":{"stack":"path"},"used":[],"i":0}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Code sorted duplicate-pruning backtracking","eyebrow":"Build the solution","summary":"Sort the values, track used positions, skip duplicate siblings, record copied complete paths, undo each choice, and return the result.","workspacePanel":"code","checkpoints":[{"id":"init-result","title":"Initialize result and used state","description":"Create the result accumulator and the used-index state for the current path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"initializes_result_accumulator","scope":"init-result","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Not storing completed permutations","Using values instead of indices for duplicate copies"],"hint":"The result collects snapshots, while used flags describe the current path.","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","used state"],"mustProve":["The solution initializes result accumulator state."],"mustNotAccept":["Only printing permutations."]}},{"id":"define-backtrack","title":"Define the recursive helper","description":"Create a helper that grows a permutation path recursively.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"defines_recursive_helper","scope":"define-backtrack","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Using fixed-depth loops","Forgetting to pass or close over the path state"],"hint":"The helper represents one partial permutation.","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","current path"],"mustProve":["The solution defines a recursive helper."],"mustNotAccept":["A non-recursive fixed-depth shell."]}},{"id":"base-case","title":"Emit complete paths","description":"When the path length equals the input length, append a copy and return.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"checks_completion_before_emit","scope":"base-case","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Emitting partial paths","Continuing to recurse after a complete path"],"hint":"A full permutation uses exactly every input position once.","semanticSpec":{"intent":"Check terminal solution state before emitting.","doneWhen":"The helper emits a snapshot only when the path is complete.","shouldFailWhen":"This step should fail if the completion branch is missing.","roles":["current path","result accumulator"],"mustProve":["The solution checks completion before emitting."],"mustNotAccept":["Appending incomplete paths."]}},{"id":"skip-used-and-duplicates","title":"Skip unavailable choices","description":"Skip indices already in the path and skip duplicate sibling branches.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"skips_invalid_candidates","scope":"skip-used","readMode":"backtracking-search-value-query-v1"}]},"commonMistakes":["Using the same index twice","Skipping duplicate copies even when the previous copy is already used in this branch"],"hint":"The duplicate check should block only repeated sibling choices.","semanticSpec":{"intent":"Skip invalid candidate choices.","doneWhen":"The helper has guards that skip unavailable candidates before choosing.","shouldFailWhen":"This step should fail if used or duplicate candidates are never skipped.","roles":["used state","choice index"],"mustProve":["The solution skips invalid candidates."],"mustNotAccept":["Generating duplicates and deduplicating after the search."]}},{"id":"choose-explore-unchoose","title":"Choose, recurse, then undo","description":"Mark an index used, append its value, recurse, then pop and unmark.","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 unmark `used[i]`","Popping before the recursive call"],"hint":"Both path and used state must be restored after each branch.","semanticSpec":{"intent":"Maintain rollback search state across recursive branches.","doneWhen":"The search state is mutated, recursion happens, and the mutation is rolled back.","shouldFailWhen":"This step should fail if choose or undo is missing.","roles":["used state","current path","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 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":["Defining the helper but never calling it","Starting with a pre-filled path"],"hint":"The first recursive state has no chosen values.","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 permutations","description":"Return the completed result accumulator.","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 recursion finishes"],"hint":"The result accumulator contains copied complete paths.","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":"Take it with you","summary":"Sort the values, build orderings by choosing unplaced positions, and refuse a duplicate that would lead the same subtree as its still-unplaced twin.","workspacePanel":"code","body":["Permutations with duplicates is plain permutations plus one guard: equal values, made adjacent by sorting, must not both lead the same arrangement.","The guard is local. Comparing each candidate to its neighbor at every slot, and skipping it only while the earlier equal copy is unplaced, keeps exactly one ordering per arrangement."],"takeaways":[{"title":"Sorting makes duplicates checkable","body":"Equal values land next to each other, so a single neighbor comparison can spot a repeated choice without scanning the whole array."},{"title":"Skip a twin only while it is unplaced","body":"Refusing nums[i] when it equals nums[i-1] and the earlier copy is unplaced cuts the redundant sibling, while still allowing the second copy deeper in the branch."},{"title":"The search only walks distinct arrangements","body":"Pruning duplicate siblings means the recursion visits about as many branches as there are unique orderings, instead of the full factorial the index approach paid for."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
