{"id":"next-permutation","title":"Next Permutation","difficulty":"medium","patterns":["two-pointers"],"primaryConcept":"sorting-partitioning","concepts":["sorting-partitioning"],"problemForm":"core","companies":["Meta","Amazon","Google","Microsoft"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length","sizes":[4,8,16,32],"valueRange":{"min":0,"max":9}},"testPlan":{"coverageContract":"practice-test-coverage-v1","requiredCoverage":["singleton","strictly-increasing","strictly-descending-wrap","all-equal","duplicate-values","pivot-at-front","pivot-in-middle","long-suffix-reversal","successor-not-last"],"requiredVisibleCoverage":["singleton","strictly-increasing","strictly-descending-wrap","all-equal","duplicate-values","pivot-at-front","pivot-in-middle","long-suffix-reversal","successor-not-last"],"notes":"Next permutation needs branch-oriented cases because random arrays mostly cover the common rightmost-pivot path."},"description":"Given an integer array `nums`, rearrange it into the lexicographically next greater permutation and return the rearranged array. If no greater permutation exists, rearrange it into the lowest possible order.","examples":[{"input":"nums = [1,2,3]","output":"[1,3,2]","explanation":"The next lexicographic ordering swaps the final two values."},{"input":"nums = [3,2,1]","output":"[1,2,3]","explanation":"This is the largest ordering, so the next permutation wraps to ascending order."},{"input":"nums = [1,1,5]","output":"[1,5,1]","explanation":"Duplicate values are allowed and still follow lexicographic order."}],"constraints":[{"id":"1-len-nums-100","text":"1 <= len(nums) <= 100","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":100}},{"id":"0-nums-i-100","text":"0 <= nums[i] <= 100","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":0,"max":100}}],"starterCode":"class Solution:\n    def nextPermutation(self, nums: list[int]) -> list[int]:\n        # Your code here\n        pass","functionName":"nextPermutation","testCases":[{"id":"1","input":{"nums":[1,2,3]},"expected":[1,3,2],"description":"Simple increasing order.","coverage":["strictly-increasing"]},{"id":"2","input":{"nums":[3,2,1]},"expected":[1,2,3],"description":"Descending order wraps around.","coverage":["strictly-descending-wrap"]},{"id":"3","input":{"nums":[1,1,5]},"expected":[1,5,1],"description":"Duplicates remain valid.","coverage":["duplicate-values"]},{"id":"4","input":{"nums":[1,3,2]},"expected":[2,1,3],"description":"Pivot is not at the final index.","coverage":["pivot-at-front","successor-not-last"]},{"id":"5","input":{"nums":[2,3,1]},"expected":[3,1,2],"description":"Suffix reversal after a middle pivot.","coverage":["pivot-at-front","successor-not-last"]},{"id":"6","input":{"nums":[1]},"expected":[1],"description":"Single value has only one permutation.","coverage":["singleton"]},{"id":"7","input":{"nums":[1,2,3,6,5,4]},"expected":[1,2,4,3,5,6],"description":"A middle pivot forces a longer suffix reversal after the swap.","coverage":["pivot-in-middle","long-suffix-reversal","successor-not-last"]},{"id":"8","input":{"nums":[1,4,3,2,2]},"expected":[2,1,2,3,4],"description":"The pivot is at the front and the successor comes from duplicate suffix values.","coverage":["duplicate-values","pivot-at-front","long-suffix-reversal","successor-not-last"]},{"id":"9","input":{"nums":[2,2,7,5,4,3]},"expected":[2,3,2,4,5,7],"description":"Repeated prefix values with a middle pivot and a multi-element suffix.","coverage":["duplicate-values","pivot-in-middle","long-suffix-reversal","successor-not-last"]},{"id":"10","input":{"nums":[2,2,2,2,2]},"expected":[2,2,2,2,2],"description":"All equal values stay unchanged because no greater ordering exists.","coverage":["all-equal","duplicate-values"]},{"id":"h1","input":{"nums":[1,2,2]},"expected":[2,1,2],"description":"Duplicate suffix values still produce the next lexicographic order.","coverage":["duplicate-values","successor-not-last"]},{"id":"h2","input":{"nums":[1,5,1]},"expected":[5,1,1],"description":"The pivot is the first element.","coverage":["duplicate-values","pivot-at-front"]},{"id":"h3","input":{"nums":[3,1,2]},"expected":[3,2,1],"description":"The pivot is in the middle of the array.","coverage":["pivot-in-middle"]},{"id":"h4","input":{"nums":[2,2,2]},"expected":[2,2,2],"description":"All equal values remain unchanged.","coverage":["all-equal","duplicate-values"]}],"hints":[{"level":1,"content":"Scan from the right to find the first place where the array can still increase."},{"level":2,"content":"Swap that pivot with the smallest larger value in the suffix."},{"level":3,"content":"Reverse the suffix so it becomes the lowest possible order after the swap."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"List every ordering, or edit the tail in place?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"generate-all","name":"Generate all permutations","summary":"Generate every permutation, sort them, and pick the next one.","decisionReason":"It builds all n factorial orderings to read one neighbour, which is exponential work for a single answer.","complexity":{"time":"O(n! * n)","space":"O(n! * n)"},"tradeoffs":["Builds every ordering in O(n! * n) time and space to surface one neighbour."],"isOptimal":false},{"id":"pivot-suffix","name":"Pivot and suffix reversal","summary":"Find the rightmost increasing pivot, swap it with the rightmost larger value, then reverse the suffix.","decisionReason":"Two right-to-left scans locate the pivot and its successor, then a swap and a tail reversal produce the next ordering in one in-place pass.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["Edits a short tail in O(n) time and O(1) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"find-pivot","title":"Find suffix pivot","description":"Scan from the right while the suffix is non-increasing.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"permutation-rearrangement","fact":"finds_nonincreasing_suffix_pivot","scope":"find-pivot","readMode":"permutation-rearrangement-value-query-v1"}]},"semanticSpec":{"intent":"Find the rightmost index where nums[i] < nums[i + 1].","doneWhen":"This step is done when the code scans backward over adjacent values until the non-increasing suffix boundary is found.","shouldFailWhen":"This step should fail if the scan starts from the left or ignores adjacent ordering.","roles":["pivot index","non-increasing suffix"],"mustProve":["A backward adjacent-order boundary scan is present."],"mustNotAccept":["Sorting the whole array immediately."],"equivalentVariants":["Use any variable names for the pivot and array."],"proofSnippets":[{"id":"py-next-permutation-find-pivot","language":"python","code":"class Solution:\n    def nextPermutation(self, nums: list[int]) -> list[int]:\n        i = len(nums) - 2\n        while i >= 0 and nums[i] >= nums[i + 1]:\n            i -= 1\n        return nums"}]},"commonMistakes":["Scanning from the left","Using the wrong comparison direction"],"hint":"The suffix after the pivot is non-increasing."},{"id":"find-successor","title":"Find successor","description":"If a pivot exists, find the rightmost suffix value greater than it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"permutation-rearrangement","fact":"finds_rightmost_successor","scope":"find-successor","readMode":"permutation-rearrangement-value-query-v1"}]},"semanticSpec":{"intent":"Find the suffix value that makes the permutation just larger.","doneWhen":"This step is done when the code scans backward for a value greater than the pivot.","shouldFailWhen":"This step should fail if equal values are accepted as successors.","roles":["pivot index","successor index"],"mustProve":["A boundary-value successor scan is present after the pivot scan."],"mustNotAccept":["Swapping with a smaller or equal value."],"equivalentVariants":["Use a right-to-left scan over the suffix."],"proofSnippets":[{"id":"py-next-permutation-find-successor","language":"python","code":"class Solution:\n    def nextPermutation(self, nums: list[int]) -> list[int]:\n        i = len(nums) - 2\n        while i >= 0 and nums[i] >= nums[i + 1]:\n            i -= 1\n        if i >= 0:\n            j = len(nums) - 1\n            while nums[j] <= nums[i]:\n                j -= 1\n        return nums"}]},"commonMistakes":["Using < instead of <=","Looking for the largest larger value instead of the rightmost larger value in the suffix"],"hint":"Because the suffix is non-increasing, the first larger value from the right is the smallest valid successor."},{"id":"swap-pivot","title":"Swap pivot and successor","description":"Exchange the pivot with the successor when a pivot exists.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"permutation-rearrangement","fact":"swaps_pivot_with_successor","scope":"swap-pivot","readMode":"permutation-rearrangement-value-query-v1"}]},"semanticSpec":{"intent":"Make the array just larger at the pivot position.","doneWhen":"This step is done when the pivot and successor indexed elements are exchanged.","shouldFailWhen":"This step should fail if only one side of the swap is assigned.","roles":["pivot index","successor index","array exchange"],"mustProve":["An indexed exchange happens after the successor is found."],"mustNotAccept":["Overwriting one element without preserving the other."],"equivalentVariants":["Use tuple assignment or a temporary variable."],"proofSnippets":[{"id":"py-next-permutation-swap-pivot","language":"python","code":"class Solution:\n    def nextPermutation(self, nums: list[int]) -> list[int]:\n        i = len(nums) - 2\n        while i >= 0 and nums[i] >= nums[i + 1]:\n            i -= 1\n        if i >= 0:\n            j = len(nums) - 1\n            while nums[j] <= nums[i]:\n                j -= 1\n            nums[i], nums[j] = nums[j], nums[i]\n        return nums"}]},"commonMistakes":["Forgetting to guard the swap when no pivot exists","Swapping with the wrong suffix value"],"hint":"Only swap when `i` is still a valid index."},{"id":"reverse-suffix","title":"Reverse suffix and return the completed permutation","description":"Reverse everything after the pivot so the suffix is the smallest possible ordering, then return the rearranged array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"permutation-rearrangement","fact":"returns_rearranged_input_sequence","scope":"reverse-suffix","readMode":"permutation-rearrangement-value-query-v1"}]},"semanticSpec":{"intent":"Minimize the suffix after the pivot increase.","doneWhen":"This step is done when the code reverses the suffix starting at i + 1 and returns the rearranged array.","shouldFailWhen":"This step should fail if the suffix is left descending after the swap.","roles":["suffix left pointer","suffix right pointer","suffix reversal"],"mustProve":["The suffix after the pivot is reversed with bounded pair exchanges."],"mustNotAccept":["Sorting or reversing the wrong prefix."],"equivalentVariants":["Use two-pointer swaps or an equivalent in-place suffix reversal."],"proofSnippets":[{"id":"py-next-permutation-reverse-suffix","language":"python","code":"class Solution:\n    def nextPermutation(self, nums: list[int]) -> list[int]:\n        i = len(nums) - 2\n        while i >= 0 and nums[i] >= nums[i + 1]:\n            i -= 1\n        if i >= 0:\n            j = len(nums) - 1\n            while nums[j] <= nums[i]:\n                j -= 1\n            nums[i], nums[j] = nums[j], nums[i]\n        left = i + 1\n        right = len(nums) - 1\n        while left < right:\n            nums[left], nums[right] = nums[right], nums[left]\n            left += 1\n            right -= 1\n        return nums"}]},"commonMistakes":["Reversing from i instead of i + 1","Forgetting that a fully descending array should reverse entirely"],"hint":"After the swap, the suffix is still descending; reverse it to make the completed permutation minimal."}],"slides":[{"id":"read-the-problem","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Find the next bigger arrangement","workspacePanel":"problem","body":["A permutation is one ordering of the same values. Line every ordering up from smallest to largest, and the task is to return the one that comes right after the current array. If the array is already the largest ordering, wrap back to the smallest.","The plainest way to find that successor is to list every ordering, sort the list, and read off the one after the input. Watch what that costs."]},{"id":"generate-all","chapter":"The problem","kind":"code-trace","eyebrow":"The plain way","title":"List every ordering, then take the next","workspacePanel":"trace","codeTrace":{"contract":"guided-code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def nextPermutation(nums: list[int]) -> list[int]:\n    def build_permutations(values: list[int], index: int, orderings: list[list[int]]) -> None:\n        if index == len(values):\n            orderings.append(values[:])\n            return\n        for swap_index in range(index, len(values)):\n            values[index], values[swap_index] = values[swap_index], values[index]\n            build_permutations(values, index + 1, orderings)\n            values[index], values[swap_index] = values[swap_index], values[index]\n    orderings: list[list[int]] = []\n    build_permutations(nums[:], 0, orderings)\n    orderings.sort()\n    idx = 0\n    while orderings[idx] != nums:\n        idx += 1\n    result: list[int] = orderings[0]\n    if idx + 1 < len(orderings):\n        result = orderings[idx + 1]\n    return result","steps":[{"id":"build-all","codeLine":11,"title":"Build every ordering","summary":"Enumerate all permutations of [1, 3, 5, 4, 2] and sort them into one long lexicographic list.","state":{"nums":[1,3,5,4,2]}},{"id":"find-input","codeLine":14,"title":"Locate the input in the list","summary":"Walk the sorted list until [1, 3, 5, 4, 2] turns up, learning where the current ordering sits.","state":{"nums":[1,3,5,4,2]}},{"id":"take-next","codeLine":18,"title":"Take the entry just after it","summary":"The neighbour one slot past the input is the answer: [1, 4, 2, 3, 5]. If the input was last, wrap to the first entry.","state":{"nums":[1,4,2,3,5]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function buildPermutations(values, index, orderings) {\n    if (index == values.length) {\n        orderings.push(Array.from(values));\n        return;\n    }\n    for (let swapIndex = index; swapIndex < values.length; swapIndex++) {\n        const entry = [values[swapIndex], values[index]];\n        values[index] = entry[0];\n        values[swapIndex] = entry[1];\n        buildPermutations(values, (index + 1), orderings);\n        const entry1 = [values[swapIndex], values[index]];\n        values[index] = entry1[0];\n        values[swapIndex] = entry1[1];\n    }\n}\nconst orderings = [];\nbuildPermutations(Array.from(nums), 0, orderings);\norderings.sort(compareSortValues);\nlet idx = 0;\nwhile (orderings[idx] != nums) {\n    idx++;\n}\nlet result = orderings[0];\nif ((idx + 1) < orderings.length) {\n    result = orderings[(idx + 1)];\n}\nreturn result;","lineMap":{"3":2,"4":3,"5":4,"6":6,"7":7,"8":10,"9":11,"10":16,"11":17,"12":18,"13":19,"14":20,"15":21,"16":23,"17":24,"18":25,"19":27},"statementBundles":{"5":{"startLine":4,"endLine":5},"7":{"startLine":7,"endLine":9},"9":{"startLine":11,"endLine":15},"15":{"startLine":21,"endLine":22},"18":{"startLine":25,"endLine":26}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function buildPermutations(values: Array<number>, index: number, orderings: Array<Array<number>>): void {\n    if (index == values.length) {\n        orderings.push(Array.from(values));\n        return;\n    }\n    for (let swapIndex = index; swapIndex < values.length; swapIndex++) {\n        const entry = [values[swapIndex], values[index]];\n        values[index] = entry[0];\n        values[swapIndex] = entry[1];\n        buildPermutations(values, (index + 1), orderings);\n        const entry1 = [values[swapIndex], values[index]];\n        values[index] = entry1[0];\n        values[swapIndex] = entry1[1];\n    }\n}\nconst orderings: Array<Array<number>> = [];\nbuildPermutations(Array.from(nums), 0, orderings);\norderings.sort(compareSortValues);\nlet idx = 0;\nwhile (orderings[idx] != nums) {\n    idx++;\n}\nlet result = orderings[0];\nif ((idx + 1) < orderings.length) {\n    result = orderings[(idx + 1)];\n}\nreturn result;","lineMap":{"3":2,"4":3,"5":4,"6":6,"7":7,"8":10,"9":11,"10":16,"11":17,"12":18,"13":19,"14":20,"15":21,"16":23,"17":24,"18":25,"19":27},"statementBundles":{"5":{"startLine":4,"endLine":5},"7":{"startLine":7,"endLine":9},"9":{"startLine":11,"endLine":15},"15":{"startLine":21,"endLine":22},"18":{"startLine":25,"endLine":26}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static void buildPermutations(List<Integer> values, int index, List<List<Integer>> orderings) {\n    if (index == values.size()) {\n        orderings.add(new ArrayList<Integer>(values));\n        return;\n    }\n    for (int swapIndex = index; swapIndex < values.size(); swapIndex++) {\n        List<Integer> entry = new ArrayList<>(List.of(values.get(swapIndex), values.get(index)));\n        values.set(index, entry.get(0));\n        values.set(swapIndex, entry.get(1));\n        buildPermutations(values, (index + 1), orderings);\n        List<Integer> entry1 = new ArrayList<>(List.of(values.get(swapIndex), values.get(index)));\n        values.set(index, entry1.get(0));\n        values.set(swapIndex, entry1.get(1));\n    }\n}\n\nList<List<Integer>> orderings = new ArrayList<>();\nbuildPermutations(new ArrayList<>(nums), 0, orderings);\norderings.sort((left, right) -> {\n    int commonLength = Math.min(left.size(), right.size());\n    for (int index = 0; index < commonLength; index++) {\n        int order = Integer.compare(left.get(index), right.get(index));\n        if (order != 0) return order;\n    }\n    return Integer.compare(left.size(), right.size());\n});\nint idx = 0;\nwhile (!Objects.equals(orderings.get(idx), nums)) {\n    idx++;\n}\nList<Integer> result = orderings.get(0);\nif ((idx + 1) < orderings.size()) {\n    result = orderings.get(idx + 1);\n}\nreturn result;","lineMap":{"3":2,"4":3,"5":4,"6":6,"7":7,"8":10,"9":11,"10":17,"11":18,"12":19,"13":27,"14":28,"15":29,"16":31,"17":32,"18":33,"19":35},"statementBundles":{"5":{"startLine":4,"endLine":5},"7":{"startLine":7,"endLine":9},"9":{"startLine":11,"endLine":15},"12":{"startLine":19,"endLine":26},"15":{"startLine":29,"endLine":30},"18":{"startLine":33,"endLine":34}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"void BuildPermutations(List<int> values, int index, List<List<int>> orderings) {\n    if (index == values.Count) {\n        orderings.Add(new List<int>(values));\n        return;\n    }\n    for (int swapIndex = index; swapIndex < values.Count; swapIndex++) {\n        List<int> entry = new() { values[swapIndex], values[index] };\n        values[index] = entry[0];\n        values[swapIndex] = entry[1];\n        BuildPermutations(values, index + 1, orderings);\n        List<int> entry1 = new() { values[swapIndex], values[index] };\n        values[index] = entry1[0];\n        values[swapIndex] = entry1[1];\n    }\n}\nList<List<int>> orderings = new();\nBuildPermutations(new List<int>(nums), 0, orderings);\nList<List<int>> orderedItems = orderings.OrderBy(value => value).ToList();\norderings.Clear();\norderings.AddRange(orderedItems);\nint idx = 0;\nwhile (orderings[idx] != nums) {\n    idx++;\n}\nList<int> result = orderings[0];\nif (idx + 1 < orderings.Count) {\n    result = orderings[idx + 1];\n}\nreturn result;","lineMap":{"3":2,"4":3,"5":4,"6":6,"7":7,"8":10,"9":11,"10":16,"11":17,"12":18,"13":21,"14":22,"15":23,"16":25,"17":26,"18":27,"19":29},"statementBundles":{"5":{"startLine":4,"endLine":5},"7":{"startLine":7,"endLine":9},"9":{"startLine":11,"endLine":15},"12":{"startLine":18,"endLine":20},"15":{"startLine":23,"endLine":24},"18":{"startLine":27,"endLine":28}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<void(vector<int>&, int, vector<vector<int>>&)> build_permutations;\n\nbuild_permutations = [&]( vector<int>& values, int index, vector<vector<int>>& orderings ) -> void {\n    if (index == values.size()) {\n        orderings.push_back(values);\n        return;\n    }\n    for (int swap_index = index; swap_index < values.size(); swap_index++) {\n        pair<int, int> entry{values[swap_index], values[index]};\n        values[index] = entry.first;\n        values[swap_index] = entry.second;\n        build_permutations(values, (index + 1), orderings);\n        pair<int, int> entry1{values[swap_index], values[index]};\n        values[index] = entry1.first;\n        values[swap_index] = entry1.second;\n    }\n};\nvector<vector<int>> orderings;\nvector<int> values = nums;\nbuild_permutations(values, 0, orderings);\nstable_sort(orderings.begin(), orderings.end());\nint idx = 0;\nwhile (orderings[idx] != nums) {\n    idx++;\n}\nvector<int> result = orderings[0];\nif ((idx + 1) < orderings.size()) {\n    result = orderings[(idx + 1)];\n}\nreturn result;","lineMap":{"3":4,"4":5,"5":6,"6":8,"7":9,"8":12,"9":13,"10":18,"11":19,"12":21,"13":22,"14":23,"15":24,"16":26,"17":27,"18":28,"19":30},"statementBundles":{"5":{"startLine":6,"endLine":7},"7":{"startLine":9,"endLine":11},"9":{"startLine":13,"endLine":17},"11":{"startLine":19,"endLine":20},"15":{"startLine":24,"endLine":25},"18":{"startLine":28,"endLine":29}}}}}},{"id":"generate-all-cost","chapter":"The problem","kind":"case-probe","eyebrow":"Count the cost","title":"How many orderings does this build for length 5 versus length 10?","workspacePanel":"trace","summary":"Every call constructs the whole sorted list before it reads a single neighbour.","options":[{"id":"factorial","label":"120 for length 5, over three million for length 10: the count is n factorial","rationale":"Each position multiplies the choices, so the list grows as n factorial, with 5! at 120 and 10! at 3,628,800, and building the full list just to read one neighbour scales out of reach fast.","isCorrect":true},{"id":"quadratic","label":"About 25 for length 5 and 100 for length 10: roughly n squared","rationale":"Orderings are not pairs of positions; every position multiplies the remaining choices, so the count is n factorial, far above n squared.","isCorrect":false},{"id":"linear","label":"5 for length 5 and 10 for length 10: one per element","rationale":"There are many orderings per element, not one. The full count multiplies the choices at each position, giving n factorial.","isCorrect":false}],"answer":"120 orderings for length 5 and 3,628,800 for length 10: the count is n factorial. Building the whole list to read one neighbour blows up long before the array gets large."},{"id":"waste-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the waste","title":"What does listing every ordering compute that the answer never uses?","workspacePanel":"trace","summary":"The answer is a single array, the one neighbour just above the input.","options":[{"id":"all-other-orderings","label":"Every other ordering, when only the one immediately above the input is wanted","rationale":"The successor differs from the input in just a short tail; building all n factorial orderings to surface one neighbour is almost entirely thrown away.","isCorrect":true},{"id":"the-sort","label":"The sort, which has to be redone for every input","rationale":"A sort runs once per call, not repeatedly. The blow-up is the number of orderings being built, not how often they are sorted.","isCorrect":false},{"id":"nothing-wasted","label":"Nothing, you must see all orderings to know which is next","rationale":"The next ordering is decided by a short rule near the end of the array, so the full list is never needed to find it.","isCorrect":false}],"answer":"The successor sits right next to the input in sorted order, so building the other 119 orderings is wasted. The next array is fixed by a small change near the tail."},{"id":"small-change-bridge","chapter":"The idea","kind":"info","eyebrow":"Where it changes","title":"The successor is a small change near the tail","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bridge-state","state":{"nums":[1,3,5,4,2]}}]},"body":["Building every ordering to read one neighbour is wasted work, so we want a local rule that edits [1, 3, 5, 4, 2] straight into its successor instead of listing the rest.","A rule like that has to know where to act. Look at [1, 3, 5, 4, 2] and find where it can climb into the next ordering."]},{"id":"where-to-grow","chapter":"The idea","kind":"case-probe","eyebrow":"Find the spot","title":"A descending tail is already as large as it can be. Where can the array still grow?","workspacePanel":"visualizer","summary":"In [1, 3, 5, 4, 2] the tail 5, 4, 2 only decreases.","options":[{"id":"first-rise","label":"At 3: the first value, scanning from the right, that is smaller than the one after it","rationale":"A run that only descends, like 5, 4, 2, is already its own largest ordering. The first earlier value that dips below its neighbour is the lowest spot that can still be raised.","isCorrect":true},{"id":"the-max","label":"At 5, the largest value in the array","rationale":"The largest value cannot grow; nothing in the array exceeds it. Growth has to happen at a value that has something bigger sitting after it.","isCorrect":false},{"id":"the-front","label":"At the front, by replacing the first value","rationale":"Changing the front swings the array far past the next ordering. The smallest increase comes from the latest position that can still be nudged up.","isCorrect":false}],"answer":"At 3, the first value from the right that is below its neighbour. The descending tail after it is already maximal, so 3 is the latest, lowest place the array can still climb: the front stays put and the change starts here, late in the array. Call it the pivot.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pivot-spot","state":{"nums":[1,3,5,4,2],"used":[2,3,4]}}]}},{"id":"which-successor","chapter":"The idea","kind":"case-probe","eyebrow":"Find the swap","title":"Which tail value should replace the pivot 3 to climb by the least?","workspacePanel":"visualizer","summary":"The pivot is 3; the descending tail after it is 5, 4, 2.","options":[{"id":"smallest-larger","label":"The 4: the smallest tail value that is still larger than 3","rationale":"Swapping in the smallest value above the pivot lifts the array by the least possible step. The 4 just clears 3, where the 5 would overshoot.","isCorrect":true},{"id":"largest","label":"The 5: the largest value in the tail","rationale":"Putting 5 where 3 was jumps further than needed, landing on a bigger ordering and skipping the true successor.","isCorrect":false},{"id":"rightmost-any","label":"The 2: the rightmost tail value","rationale":"The 2 is smaller than 3, so moving it to the pivot lowers the array instead of raising it.","isCorrect":false}],"answer":"The 4, the smallest tail value above 3. It raises the array by the least. Because the tail descends, that value is also the rightmost one still greater than the pivot.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"successor-pick","state":{"nums":[1,3,5,4,2],"i":1}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"List every ordering, or edit the tail in place?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"nums":[1,3,5,4,2],"i":1,"j":3}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Walk one array to its successor","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"nums":[1,3,5,4,2]}}]},"body":["Take nums = [1, 3, 5, 4, 2]. The goal is the immediate successor, the smallest ordering still larger than this one.","Predict each move on the array below: find where it can climb, decide what to do there, and watch the array settle into its next ordering."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the moves","title":"Step [1, 3, 5, 4, 2] up to its successor","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"find-pivot","state":{"nums":[1,3,5,4,2]}},{"id":"find-successor","state":{"nums":[1,3,5,4,2],"i":1,"j":3}},{"id":"after-swap","state":{"nums":[1,4,5,3,2],"i":1}},{"id":"after-reverse","state":{"nums":[1,4,2,3,5],"left":2,"right":4}}]},"beats":[{"id":"find-pivot","title":"Scanning from the right, which value is the pivot?","summary":"The tail 5, 4, 2 only descends.","prompt":"The scan is moving right to left across 2, 4, 5, 3.","options":[{"id":"three","label":"3, at index 1","rationale":"3 is the first value from the right that is smaller than its neighbour (the 5), so it is the lowest position that can still be raised.","isCorrect":true},{"id":"two","label":"2, the last value","rationale":"The last value has no neighbour after it to compare against; the pivot is the first dip found scanning inward.","isCorrect":false},{"id":"one","label":"1, at the front","rationale":"The scan stops at the first dip it meets from the right, which is 3, before it ever reaches the front.","isCorrect":false}],"answer":"3 at index 1. The tail after it is fully descending, so 3 is the pivot to raise."},{"id":"find-successor","title":"Which tail value swaps into the pivot?","summary":"The pivot is 3; the tail is 5, 4, 2.","prompt":"The pivot is 3 and the tail descends as 5, 4, 2.","options":[{"id":"four","label":"4, at index 3","rationale":"From the right, 2 is below 3 and skipped; 4 is the first value above 3, and being smallest of the larger ones it raises the array by the least.","isCorrect":true},{"id":"five","label":"5, at index 2","rationale":"5 is above 3 but larger than the 4, so swapping it in overshoots the immediate successor.","isCorrect":false},{"id":"two-succ","label":"2, at index 4","rationale":"2 is smaller than the pivot, so it would shrink the array, not grow it.","isCorrect":false}],"answer":"4 at index 3. Swapping 3 and 4 gives [1, 4, 5, 3, 2], lifting the array by the smallest step."},{"id":"after-swap","title":"After the swap the tail is 5, 3, 2. What finishes the successor?","summary":"The array is now [1, 4, 5, 3, 2]; the tail after the pivot still descends.","prompt":"After swapping, the suffix after the pivot is 5, 3, 2.","options":[{"id":"reverse","label":"Reverse the tail after the pivot so it runs low to high","rationale":"A descending tail is the largest arrangement of those values; reversing it to 2, 3, 5 makes the smallest, giving the immediate next ordering.","isCorrect":true},{"id":"sort-all","label":"Sort the whole array from the front","rationale":"Sorting everything would discard the raised pivot and collapse to the smallest ordering below the current raised prefix.","isCorrect":false},{"id":"leave","label":"Leave the tail as it is","rationale":"Leaving 5, 3, 2 keeps the tail at its maximum, so the array overshoots the true successor.","isCorrect":false}],"answer":"Reverse the tail: 5, 3, 2 becomes 2, 3, 5, so the array is [1, 4, 2, 3, 5], the next ordering up."},{"id":"after-reverse","title":"The tail is reversed. How does [1, 4, 2, 3, 5] compare to the input?","summary":"The pivot rose from 3 to 4 and the tail now ascends as 2, 3, 5.","prompt":"The front 1 is unchanged; the change starts at the pivot slot and runs to the end.","options":[{"id":"just-above","label":"It is the smallest ordering that is still larger than [1, 3, 5, 4, 2]","rationale":"Raising the pivot by the least and then minimizing the tail lands exactly on the next ordering, with no ordering squeezed between.","isCorrect":true},{"id":"much-larger","label":"It is the largest ordering of these values","rationale":"The largest ordering is the fully descending [5, 4, 3, 2, 1]; this result barely clears the input by design.","isCorrect":false},{"id":"equal","label":"It is a re-shuffle of the same size, neither larger nor smaller","rationale":"Orderings are strictly ranked, and this one sits one step above the input, so it is larger, not equal.","isCorrect":false}],"answer":"It is the immediate successor: the smallest ordering strictly above [1, 3, 5, 4, 2], reached by raising the pivot the least and minimizing the tail."}]},{"id":"successor-equal-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can the successor scan stop at the first value that is not smaller than the pivot?","workspacePanel":"trace","summary":"Stopping the tail scan at the first value not smaller than the pivot looks fine, and it passes every test with distinct values. But a tail value can equal the pivot, and a loose stop never asks whether the value it found is actually larger. Watch it run on [1, 5, 1].","pitfall":"The successor scan below stops on the first tail value that is not strictly smaller than the pivot.","whyItMatters":"On [1, 5, 1] the pivot is the leading 1, and the scan halts on the trailing 1 because it is not smaller. Swapping two equal values changes nothing, the reverse then runs, and the result is [1, 1, 5], which is below the input. Use a strict greater-than test so the successor truly raises the pivot; the correct answer is [5, 1, 1].","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"i = len(nums) - 2\nwhile i >= 0 and nums[i] >= nums[i + 1]:\n    i -= 1\nj = len(nums) - 1\nwhile nums[j] < nums[i]:\n    j -= 1\nnums[i], nums[j] = nums[j], nums[i]\nleft = i + 1\nright = len(nums) - 1\nwhile left < right:\n    nums[left], nums[right] = nums[right], nums[left]\n    left += 1\n    right -= 1","steps":[{"id":"pit-pivot","title":"Pivot is the leading 1","codeLine":3,"summary":"On [1, 5, 1] the scan stops at index 0: nums[0]=1 is below nums[1]=5, so the pivot is the front 1.","state":{"nums":[1,5,1],"i":0}},{"id":"pit-grab-equal","title":"The tail scan stops on the trailing 1","codeLine":5,"summary":"Scanning the tail from the right, nums[2]=1 is not smaller than the pivot 1, so the loose test halts here and treats the equal value as the successor.","state":{"nums":[1,5,1],"i":0,"j":2}},{"id":"pit-swap","title":"Swapping two equal values changes nothing","codeLine":7,"summary":"Exchanging the pivot 1 with the equal 1 leaves the array as [1, 5, 1]; the pivot was never actually raised.","state":{"nums":[1,5,1],"i":0,"j":2}},{"id":"pit-wrong","title":"Below the input, not above it","codeLine":11,"summary":"Reversing the tail after index 0 turns [1, 5, 1] into [1, 1, 5], which is smaller than [1, 5, 1]. The real successor is [5, 1, 1].","state":{"nums":[1,1,5],"left":1,"right":2}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let i = nums.length - 2;\nwhile ((i >= 0) && (nums[i] >= nums[(i + 1)])) {\n    i--;\n}\nlet j = nums.length - 1;\nwhile (nums[j] < nums[i]) {\n    j--;\n}\nconst entry = [nums[j], nums[i]];\nnums[i] = entry[0];\nnums[j] = entry[1];\nlet left = i + 1;\nlet right = nums.length - 1;\nwhile (left < right) {\n    const entry1 = [nums[right], nums[left]];\n    nums[left] = entry1[0];\n    nums[right] = entry1[1];\n    left++;\n    right--;\n}","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":9,"8":12,"9":13,"10":14,"11":15,"12":18,"13":19},"statementBundles":{"3":{"startLine":3,"endLine":4},"6":{"startLine":7,"endLine":8},"7":{"startLine":9,"endLine":11},"11":{"startLine":15,"endLine":17},"13":{"startLine":19,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let i = nums.length - 2;\nwhile ((i >= 0) && (nums[i] >= nums[(i + 1)])) {\n    i--;\n}\nlet j = nums.length - 1;\nwhile (nums[j] < nums[i]) {\n    j--;\n}\nconst entry = [nums[j], nums[i]];\nnums[i] = entry[0];\nnums[j] = entry[1];\nlet left = i + 1;\nlet right = nums.length - 1;\nwhile (left < right) {\n    const entry1 = [nums[right], nums[left]];\n    nums[left] = entry1[0];\n    nums[right] = entry1[1];\n    left++;\n    right--;\n}","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":9,"8":12,"9":13,"10":14,"11":15,"12":18,"13":19},"statementBundles":{"3":{"startLine":3,"endLine":4},"6":{"startLine":7,"endLine":8},"7":{"startLine":9,"endLine":11},"11":{"startLine":15,"endLine":17},"13":{"startLine":19,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int i = nums.size() - 2;\nwhile ((i >= 0 && nums.get(i) >= nums.get(i + 1))) {\n    i--;\n}\nint j = nums.size() - 1;\nwhile (nums.get(j) < nums.get(i)) {\n    j--;\n}\nList<Integer> entry = new ArrayList<>(List.of(nums.get(j), nums.get(i)));\nnums.set(i, entry.get(0));\nnums.set(j, entry.get(1));\nint left = i + 1;\nint right = nums.size() - 1;\nwhile (left < right) {\n    List<Integer> entry1 = new ArrayList<>(List.of(nums.get(right), nums.get(left)));\n    nums.set(left, entry1.get(0));\n    nums.set(right, entry1.get(1));\n    left++;\n    right--;\n}","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":9,"8":12,"9":13,"10":14,"11":15,"12":18,"13":19},"statementBundles":{"3":{"startLine":3,"endLine":4},"6":{"startLine":7,"endLine":8},"7":{"startLine":9,"endLine":11},"11":{"startLine":15,"endLine":17},"13":{"startLine":19,"endLine":20}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int i = nums.Count - 2;\nwhile (i >= 0 && nums[i] >= nums[i + 1]) {\n    i--;\n}\nint j = nums.Count - 1;\nwhile (nums[j] < nums[i]) {\n    j--;\n}\nList<int> entry = new() { nums[j], nums[i] };\nnums[i] = entry[0];\nnums[j] = entry[1];\nint left = i + 1;\nint right = nums.Count - 1;\nwhile (left < right) {\n    List<int> entry1 = new() { nums[right], nums[left] };\n    nums[left] = entry1[0];\n    nums[right] = entry1[1];\n    left++;\n    right--;\n}","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":9,"8":12,"9":13,"10":14,"11":15,"12":18,"13":19},"statementBundles":{"3":{"startLine":3,"endLine":4},"6":{"startLine":7,"endLine":8},"7":{"startLine":9,"endLine":11},"11":{"startLine":15,"endLine":17},"13":{"startLine":19,"endLine":20}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int i = nums.size() - 2;\nwhile ((i >= 0 && nums[i] >= nums[(i + 1)])) {\n    i--;\n}\nint j = nums.size() - 1;\nwhile (nums[j] < nums[i]) {\n    j--;\n}\npair<int, int> entry{nums[j], nums[i]};\nnums[i] = entry.first;\nnums[j] = entry.second;\nint left = i + 1;\nint right = nums.size() - 1;\nwhile (left < right) {\n    pair<int, int> entry1{nums[right], nums[left]};\n    nums[left] = entry1.first;\n    nums[right] = entry1.second;\n    left++;\n    right--;\n}","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":9,"8":12,"9":13,"10":14,"11":15,"12":18,"13":19},"statementBundles":{"3":{"startLine":3,"endLine":4},"6":{"startLine":7,"endLine":8},"7":{"startLine":9,"endLine":11},"11":{"startLine":15,"endLine":17},"13":{"startLine":19,"endLine":20}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"The strict successor test held the duplicate case together. A couple of shapes lean on the boundaries instead.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"nums":[5,4,3]}}]},"body":["The three moves assume a pivot exists and a tail follows it. Two inputs push on those assumptions: nums = [5, 4, 3] and nums = [7].","Both test the boundaries of the pivot scan rather than its usual middle case. Work through what each one does to the scan, the swap, and the reversal."]},{"id":"no-pivot-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Push the boundary","title":"With nums = [5, 4, 3] the pivot scan runs off the front. What should happen?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-pivot-state","state":{"nums":[5,4,3]}}]},"options":[{"id":"reverse-whole","label":"Skip the swap and reverse the whole array into ascending order","rationale":"A fully descending array is the largest ordering, so its successor wraps to the smallest. With no pivot, reversing everything gives [3, 4, 5].","isCorrect":true},{"id":"return-same","label":"Return the array unchanged","rationale":"The problem says the largest ordering must wrap to the lowest, so [5, 4, 3] becomes [3, 4, 5], not itself.","isCorrect":false},{"id":"swap-ends","label":"Swap the first and last values","rationale":"Swapping the ends gives [3, 4, 5] here by luck, but on a longer descending array it leaves the middle out of order. The rule is to reverse the whole array.","isCorrect":false}],"answer":"With no pivot, the array is already maximal, so it wraps: skip the swap and reverse the whole array, turning [5, 4, 3] into [3, 4, 5].","summary":"Every adjacent pair descends, so no value is below its neighbour and the scan passes index 0."},{"id":"single-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Shrink it down","title":"With nums = [7], where does the pivot scan even start?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-state","state":{"nums":[7]}}]},"options":[{"id":"before-front","label":"Before the front: the scan starts past index 0 and the array is returned as is","rationale":"For one element the starting index is -1, so the scan body never runs, no swap happens, and reversing a single value leaves it alone.","isCorrect":true},{"id":"index-zero","label":"At index 0, comparing 7 with the value after it","rationale":"There is no value after index 0, so the scan cannot start there; it begins at the second-to-last slot, which is before the front.","isCorrect":false},{"id":"crash","label":"It reads past the end and fails","rationale":"Starting at index -1 means the loop guard is false immediately, so nothing is read out of bounds.","isCorrect":false}],"answer":"The scan starts at index -1, before the front, so it never runs. No swap, and reversing one value is a no-op, so [7] is returned unchanged.","summary":"The pivot scan begins one slot before the last index, comparing a value with its neighbour."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"One scan finds the pivot, a second finds its successor, then a swap and a tail reversal, with a strict comparison guarding the duplicate case.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[1,3,5,4,2],"i":1}}]},"body":["Scan from the right to the pivot, the first value below its neighbour. Scan the tail from the right to the rightmost value strictly greater than the pivot, and swap the two. Then reverse the tail after the pivot so it runs low to high.","The subtlety the moves hinge on: the successor test must be strict, and when no pivot is found the swap is skipped while the reversal still runs, wrapping a maximal array back to the smallest ordering."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the pivot, swap, and reverse","summary":"Now build it: scan from the right for the pivot, the first value below its neighbour, then scan the tail for the rightmost value strictly above it, swap the two, and reverse the tail after the pivot so it runs low to high.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","body":["The next ordering changes only a short tail: raise the lowest position that can still climb, then make everything after it as small as possible.","The pivot is the first value below its neighbour from the right; its successor is the rightmost tail value strictly above it; reversing the descending tail after the swap finishes the immediate next ordering."],"takeaways":[{"title":"Grow at the pivot","body":"The first value from the right that dips below its neighbour is the lowest spot that can still rise; the descending tail past it is already maximal."},{"title":"Raise it by the least","body":"Swapping in the smallest tail value above the pivot lifts the array by the smallest step, and because the tail descends that value is the rightmost one greater than the pivot."},{"title":"Reverse, do not sort","body":"After the swap the tail still descends, so reversing it gives the smallest tail; with no pivot, reversing the whole array wraps a maximal input to the smallest ordering."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
