{"id":"partition-array-according-to-given-pivot","title":"Partition Array According to Given Pivot","difficulty":"medium","patterns":["sorting-linear"],"primaryConcept":"sorting-linear","concepts":["sorting-linear"],"problemForm":"application","companies":["Amazon","Google","Meta","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array-scalar","primaryParam":"nums","sizeMetric":"array-length","valueRange":{"min":-20,"max":20},"secondaryParams":{"pivot":{"strategy":"random-int","value":{"min":-10,"max":10}}},"sizes":[8,16,32,64]},"description":"Given an integer array `nums` and an integer `pivot`, return a new array where every value less than `pivot` comes first, followed by every value equal to `pivot`, followed by every value greater than `pivot`.\n\nThe relative order of values within each of the three groups must stay the same as in the original array.","examples":[{"input":"nums = [9,12,5,10,14,3,10], pivot = 10","output":"[9,5,3,10,10,12,14]","explanation":"Values below 10 keep their original order, then the two 10s, then values above 10 in original order."},{"input":"nums = [-3,4,3,2], pivot = 2","output":"[-3,2,4,3]","explanation":"-3 is less than the pivot, 2 equals it, and 4 then 3 are greater."}],"constraints":[{"id":"1-len-nums-10-5","text":"1 <= len(nums) <= 10^5","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":100000}},{"id":"10-6-nums-i-10-6","text":"-10^6 <= nums[i] <= 10^6","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-1000000,"max":1000000}},{"id":"10-6-pivot-10-6","text":"-10^6 <= pivot <= 10^6","check":{"kind":"valueRange","target":"pivot","selector":"value","min":-1000000,"max":1000000}}],"starterCode":"class Solution:\n    def pivotArray(self, nums: list[int], pivot: int) -> list[int]:\n        # Your code here\n        pass","functionName":"pivotArray","testCases":[{"id":"1","input":{"nums":[9,12,5,10,14,3,10],"pivot":10},"expected":[9,5,3,10,10,12,14],"description":"Mixed values on both sides of the pivot."},{"id":"2","input":{"nums":[-3,4,3,2],"pivot":2},"expected":[-3,2,4,3],"description":"Negative value, pivot value, and greater values."},{"id":"3","input":{"nums":[1,1,1],"pivot":1},"expected":[1,1,1],"description":"All values equal the pivot."},{"id":"4","input":{"nums":[5,4,3],"pivot":2},"expected":[5,4,3],"description":"Every value is greater than the pivot and order is preserved."},{"id":"5","input":{"nums":[0,-2,-2,0,3],"pivot":-2},"expected":[-2,-2,0,0,3],"description":"Duplicate pivot values stay together after the less-than group."},{"id":"6","input":{"nums":[-5,-1,0],"pivot":4},"expected":[-5,-1,0],"description":"Every value is less than the pivot and order is preserved."},{"id":"h1","input":{"nums":[2,1,2,3,2],"pivot":2},"description":"Every group contains repeated pivot values.","expected":[1,2,2,2,3]},{"id":"h2","input":{"nums":[0,1,-1,0],"pivot":0},"description":"Negative values appear before the pivot group.","expected":[-1,0,0,1]},{"id":"h3","input":{"nums":[7,6,5],"pivot":7},"description":"The pivot lands after all smaller values.","expected":[6,5,7]},{"id":"h4","input":{"nums":[1,4,2,5,3],"pivot":3},"description":"Less-than, equal, and greater groups all appear.","expected":[1,2,3,4,5]},{"id":"topup-many-pivots","input":{"nums":[9,1,5,5,2,5,7],"pivot":5},"expected":[1,2,5,5,5,9,7],"description":"Multiple pivot values stay in their original relative order."},{"id":"topup-no-smaller-values","input":{"nums":[6,7,6,5],"pivot":5},"expected":[5,6,7,6],"description":"When no values are smaller, pivot values come before larger values."}],"hints":[{"level":1,"content":"Stable partitioning means each group preserves the order it had in the input."},{"level":2,"content":"Append values below the pivot first, then values equal to it, then values above it."},{"level":3,"content":"Three linear scans are still O(n), and each scan has a single simple comparison."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Pick the one whose cost and order guarantee match the contract.","approaches":[{"id":"sort-by-band","name":"Sort the values by band","summary":"Rank each value 0, 1, or 2 for its band and sort the array on that rank.","decisionReason":"It returns the right groups, but it compares values against each other to order bands that the pivot alone already settles.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Sorting keeps the bands ordered, but the value-to-value comparisons are work the answer never needed."],"isOptimal":false},{"id":"stable-three-pass","name":"Three stable scans","summary":"Scan once for values below the pivot, again for equal values, again for greater values, appending in scan order.","decisionReason":"Each scan appends in input order, so every band keeps its values exactly as nums had them: the below band still reads 9, 5, 3. Three passes over n values cost O(n).","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Three passes touch the array three times, but each is a single comparison and an append, no value-to-value ordering."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-result","title":"Initialize result","description":"Create the empty result that the three scans will append to.","commonMistakes":["Sorting `nums` in place and losing the within-band original order","Returning a count of values instead of an array"],"hint":"Start with an empty result sequence.","semanticSpec":{"intent":"Create a result sequence before scanning the input values.","doneWhen":"The method initializes an empty sequence used as the returned partitioned array.","shouldFailWhen":"This step should fail if there is no result sequence for collecting partition groups.","roles":["input sequence","result sequence"],"mustProve":["A result sequence is initialized before values are appended."],"mustNotAccept":["Only mutating or sorting the input without creating a result sequence."],"equivalentVariants":["Use a list named `result`, `answer`, or another equivalent result state."],"proofSnippets":[{"id":"py-pivot-array-init-result","language":"python","code":"class Solution:\n    def pivotArray(self, nums: list[int], pivot: int) -> list[int]:\n        result = []\n        return result"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]}},{"id":"scan-values","title":"Scan input values","description":"Iterate through `nums` so each value can be tested against the pivot.","commonMistakes":["Comparing only adjacent values instead of each value to the pivot","Scanning once and trying to place all three bands in that single pass"],"hint":"Each band is a scan over the same input sequence.","semanticSpec":{"intent":"Scan the input sequence so every value can be tested against the pivot.","doneWhen":"The code iterates through `nums` while reading each scanned value.","shouldFailWhen":"This step should fail if the input sequence is never scanned.","roles":["input sequence","scan value","pivot"],"mustProve":["The input array is scanned using a loop over its values."],"mustNotAccept":["Only checking a single fixed index.","Using a sort call without scanning values for partitioning."],"equivalentVariants":["Use direct value iteration or indexed iteration over the full input sequence."],"proofSnippets":[{"id":"py-pivot-array-scan-values","language":"python","code":"class Solution:\n    def pivotArray(self, nums: list[int], pivot: int) -> list[int]:\n        result = []\n        for num in nums:\n            if num < pivot:\n                pass\n        return result"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]}},{"id":"append-groups","title":"Append the bands in order","description":"Append each value to the result in below, then equal, then above pivot order.","commonMistakes":["Appending pivot-equal values before the below-pivot values","Collapsing the below and equal bands into one comparison"],"hint":"Append each matching value as the scan reaches it, so a band comes out in input order.","semanticSpec":{"intent":"Build the result by appending scanned values in band order instead of reordering them.","doneWhen":"Values from `nums` are appended to the result sequence as scan values.","shouldFailWhen":"This step should fail if values are counted but never appended to the result.","roles":["scan value","result sequence","pivot group"],"mustProve":["Scanned input values are appended to the result sequence."],"mustNotAccept":["Appending derived counts instead of original values.","Returning a sorted copy from a library call."],"equivalentVariants":["Use three passes, three temporary lists that are concatenated, or another stable append-based construction."],"proofSnippets":[{"id":"py-pivot-array-append-groups","language":"python","code":"class Solution:\n    def pivotArray(self, nums: list[int], pivot: int) -> list[int]:\n        result = []\n        for num in nums:\n            if num < pivot:\n                result.append(num)\n        for num in nums:\n            if num == pivot:\n                result.append(num)\n        for num in nums:\n            if num > pivot:\n                result.append(num)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"appends_scan_state_to_result","scope":"append-to-result","readMode":"array-scan-value-query-v1"}]}},{"id":"return-result","title":"Return the partitioned array","description":"Return the result sequence after the three bands have been appended.","commonMistakes":["Returning only the equal-to-pivot band","Returning the original `nums` unchanged"],"hint":"The collected result is the final partitioned array.","semanticSpec":{"intent":"Return the constructed result sequence as the answer.","doneWhen":"The method returns the result sequence produced by appending scanned values.","shouldFailWhen":"This step should fail if the method returns a scalar, a count, or the unmodified input.","roles":["result sequence","terminal return"],"mustProve":["The terminal return is the appended result sequence."],"mustNotAccept":["Returning the pivot.","Returning a count of values in each group."],"equivalentVariants":["Return a concatenation of stable band arrays if those arrays were built by scanning `nums`."],"proofSnippets":[{"id":"py-pivot-array-return-result","language":"python","code":"class Solution:\n    def pivotArray(self, nums: list[int], pivot: int) -> list[int]:\n        result = []\n        for num in nums:\n            if num < pivot:\n                result.append(num)\n        return result"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]}}],"slides":[{"id":"read-the-signal","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Split around a pivot, keep the order","workspacePanel":"problem","body":["You are given an array and a pivot value. Return a new array where every value below the pivot comes first, then every value equal to it, then every value above it. Inside each of those three bands the values must stay in the order they had in the input.","Sorting is the reflex here. It has to survive the second requirement, that nothing inside a band moves relative to the other values in that band."]},{"id":"sort-by-band","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Sort the values into band order","summary":"Tagging each value with its band and bubble-sorting on the tag returns the right order. Follow which values get compared to which along the way.","workspacePanel":"trace","body":["Give each value a rank of 0, 1, or 2 for its band, then sort by swapping out-of-order neighbors."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def pivotArray(nums: list[int], pivot: int) -> list[int]:\n    def rank(x: int) -> int:\n        return 0 if x < pivot else (1 if x == pivot else 2)\n    result = list(nums)\n    for i in range(len(result)):\n        for j in range(len(result) - 1 - i):\n            if rank(result[j]) > rank(result[j + 1]):\n                result[j], result[j + 1] = result[j + 1], result[j]\n    return result","steps":[{"id":"tag-values","title":"Each value gets a band rank","codeLine":3,"summary":"nums = [9, 12, 5, 10, 14, 3, 10], pivot = 10. Every value carries a rank of 0, 1, or 2, and the sort orders the array by rank.","state":{"nums":[9,12,5,10,14,3,10],"pivot":10}},{"id":"sort-compares","title":"Neighbors are compared and swapped","codeLine":7,"summary":"rank(12) is 2 and rank(5) is 0, so the two neighbors swap: [9, 5, 12, 10, 14, 3, 10]. Each pass checks the neighbor pairs left in its shrinking range this way.","state":{"nums":[9,5,12,10,14,3,10],"i":2,"pivot":10}},{"id":"sorted-out","title":"It lands on the right answer","codeLine":9,"summary":"Equal ranks never swap, so same-band values keep their positions and the result is [9, 5, 3, 10, 10, 12, 14]. Getting there took 21 neighbor comparisons across six passes.","state":{"nums":[9,5,3,10,10,12,14],"pivot":10}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function rank(x) {\n    return (x < pivot ? 0 : (x === pivot ? 1 : 2));\n}\nconst result = Array.from(nums);\nfor (let i = 0; i < result.length; i++) {\n    for (let j = 0; j < ((result.length - 1) - i); j++) {\n        if (rank(result[j]) > rank(result[(j + 1)])) {\n            const entry = [result[(j + 1)], result[j]];\n            result[j] = entry[0];\n            result[(j + 1)] = entry[1];\n        }\n    }\n}\nreturn result;","lineMap":{"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":14},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function rank(x: number): number {\n    return (x < pivot ? 0 : (x === pivot ? 1 : 2));\n}\nconst result = Array.from(nums);\nfor (let i = 0; i < result.length; i++) {\n    for (let j = 0; j < ((result.length - 1) - i); j++) {\n        if (rank(result[j]) > rank(result[(j + 1)])) {\n            const entry = [result[(j + 1)], result[j]];\n            result[j] = entry[0];\n            result[(j + 1)] = entry[1];\n        }\n    }\n}\nreturn result;","lineMap":{"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":14},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int Rank(int x) {\n    return (x < pivot ? 0 : (x == pivot ? 1 : 2));\n    return 0;\n}\nList<int> result = new(nums);\nfor (int i = 0; i < result.Count; i++) {\n    for (int j = 0; j < result.Count - 1 - i; j++) {\n        if (Rank(result[j]) > Rank(result[j + 1])) {\n            List<int> entry = new() { result[j + 1], result[j] };\n            result[j] = entry[0];\n            result[j + 1] = entry[1];\n        }\n    }\n}\nreturn result;","lineMap":{"3":2,"4":5,"5":6,"6":7,"7":8,"8":9,"9":15},"statementBundles":{"3":{"startLine":2,"endLine":4},"8":{"startLine":9,"endLine":14}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"auto rank = [&]( int x ) -> int {\n    return (x < pivot ? 0 : (x == pivot ? 1 : 2));\n};\nvector<int> result = nums;\nfor (int i = 0; i < result.size(); i++) {\n    for (int j = 0; j < ((result.size() - 1) - i); j++) {\n        if (rank(result[j]) > rank(result[(j + 1)])) {\n            pair<int, int> entry{result[(j + 1)], result[j]};\n            result[j] = entry.first;\n            result[(j + 1)] = entry.second;\n        }\n    }\n}\nreturn result;","lineMap":{"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":14},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":13}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int rank(int x, int pivot) {\n    return (x < pivot ? 0 : (x == pivot ? 1 : 2));\n}\n\nList<Integer> result = new ArrayList<Integer>(nums);\nfor (int i = 0; i < result.size(); i++) {\n    for (int j = 0; j < ((result.size() - 1) - i); j++) {\n        if (rank(result.get(j), pivot) > rank(result.get(j + 1), pivot)) {\n            List<Integer> entry = new ArrayList<>(List.of(result.get(j + 1), result.get(j)));\n            result.set(j, entry.get(0));\n            result.set((j + 1), entry.get(1));\n        }\n    }\n}\nreturn result;","lineMap":{"3":2,"4":5,"5":6,"6":7,"7":8,"8":9,"9":15},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":9,"endLine":14}}}}}},{"id":"waste-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the waste","title":"Which comparisons does the sort make that the answer never asked for?","workspacePanel":"trace","summary":"The sort runs pass after pass, swapping neighboring values into band order.","options":[{"id":"value-to-value","label":"Comparing one value against another value","rationale":"The band each value belongs to is fixed by the pivot alone, so every comparison between two values is work the answer does not depend on.","isCorrect":true},{"id":"value-to-pivot","label":"Comparing each value against the pivot","rationale":"Every value has to be located against the pivot at some point, and the ranks this sort reads came from exactly that check.","isCorrect":false},{"id":"recount-length","label":"Recounting the array length on every pass","rationale":"Reading the length is cheap. The repeated work comes from comparing neighboring values as the passes run.","isCorrect":false}],"answer":"The swap driven by rank(12) > rank(5) moved 5 ahead of 12, but the pivot had already settled which band each of them belonged to before the sort started."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"Which fact about each value, asked once, decides where it goes?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pattern-quiz-state","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10]},{"name":"result","values":[]}],"pivot":10}}]},"quiz":{"contract":"pattern-recognition-v1","question":"Which fact about each value, asked once, decides where it goes?","signalPrompt":"Every value belongs to exactly one band around the pivot, and the bands keep their input order.","options":[{"id":"sorting-linear","label":"Whether the value is below, equal to, or above the pivot","signal":"One comparison to the pivot sorts each value into a fixed band, with no value-to-value comparison.","rationale":"A single comparison per value names its band, and no pair of values ever has to be ranked against each other.","isCorrect":true},{"id":"sorting-divide-conquer","label":"How each value ranks against the other values","signal":"Full ordering is what a comparison sort computes by pitting values against each other.","rationale":"Ranking values against each other is more than the problem needs: the bands are decided by the pivot alone.","isCorrect":false},{"id":"heap","label":"Which value is currently the smallest unplaced one","signal":"A heap repeatedly surfaces the minimum, which orders values but scrambles their original positions.","rationale":"Pulling the minimum each time reorders within a band, breaking the required original order.","isCorrect":false},{"id":"binary-search","label":"Where the pivot would sit in a sorted version of the array","signal":"Binary search locates a boundary, but only inside an already-sorted range.","rationale":"There is no sorted range to query here, and the values inside a band must stay unsorted.","isCorrect":false}],"missFeedback":"The deciding fact is the result of one comparison to the pivot: below, equal, or above.","hint":"For each value the only question is below, equal, or above the pivot."}},{"id":"order-is-free-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Find the rule","title":"If we append values as we scan, what order does a band end up in?","workspacePanel":"visualizer","summary":"In nums the below-pivot values 9, 5, and 3 sit at positions 0, 2, and 5.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"order-is-free-state","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":0},{"name":"result","values":[]}],"pivot":10}}]},"options":[{"id":"scan-order","label":"The order they were scanned: 9, 5, 3","rationale":"Appending as you reach each value records the input order directly, which is exactly the stability the contract asks for.","isCorrect":true},{"id":"ascending","label":"Ascending: 3, 5, 9","rationale":"Sorting within a band is the work we are trying to drop. The contract asks for the order the values had in nums.","isCorrect":false},{"id":"reversed","label":"Reversed: 3, 5, 9 read back to front","rationale":"A forward scan appends front to back, so the first value scanned is the first appended. Nothing reverses it.","isCorrect":false}],"answer":"A forward scan reaches 9 first and 3 last, so appending as it goes writes 9, 5, 3. The band comes out in input order with no comparison made inside it."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which approach should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10]},{"name":"result","values":[9,5,3,10,10,12,14]}],"pivot":10}}]},"selection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Pick the one whose cost and order guarantee match the contract.","approaches":[{"id":"sort-by-band","name":"Sort the values by band","summary":"Rank each value 0, 1, or 2 for its band and sort the array on that rank.","decisionReason":"It returns the right groups, but it compares values against each other to order bands that the pivot alone already settles.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Sorting keeps the bands ordered, but the value-to-value comparisons are work the answer never needed."],"isOptimal":false},{"id":"stable-three-pass","name":"Three stable scans","summary":"Scan once for values below the pivot, again for equal values, again for greater values, appending in scan order.","decisionReason":"Each scan appends in input order, so every band keeps its values exactly as nums had them: the below band still reads 9, 5, 3. Three passes over n values cost O(n).","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Three passes touch the array three times, but each is a single comparison and an append, no value-to-value ordering."],"isOptimal":true}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"An empty result, three scans to come","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":0},{"name":"result","values":[]}],"pivot":10}}]},"body":["Take nums = [9, 12, 5, 10, 14, 3, 10], pivot = 10, and an empty result.","Each scan walks the whole array and appends the values that match its own comparison, one scan after another."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the scans","title":"Fill the result one scan at a time","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":0},{"name":"result","values":[]}],"pivot":10}},{"id":"below-scan","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":5},{"name":"result","values":[9,5,3]}],"pivot":10}},{"id":"equal-scan","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":6},{"name":"result","values":[9,5,3,10,10]}],"pivot":10}},{"id":"above-scan","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":4},{"name":"result","values":[9,5,3,10,10,12,14]}],"pivot":10}}]},"beats":[{"id":"below-scan","title":"The first scan keeps only values below 10. What is the result so far?","summary":"nums = [9, 12, 5, 10, 14, 3, 10], pivot = 10, and the result started empty.","prompt":"The below-pivot scan has just finished.","options":[{"id":"below-correct","label":"[9, 5, 3]","rationale":"9, 5, and 3 are the values below 10, appended in the order the scan reached them.","isCorrect":true},{"id":"below-sorted","label":"[3, 5, 9]","rationale":"That is the below band sorted. The scan appends in input order, so 9 comes first.","isCorrect":false},{"id":"below-with-pivot","label":"[9, 5, 3, 10, 10]","rationale":"The pivot values belong to the second scan. The first scan stops at strictly-below values.","isCorrect":false}],"answer":"The below scan produces [9, 5, 3], in the order they appeared."},{"id":"equal-scan","title":"The second scan appends the 10s. Where do they land?","summary":"Two values equal 10. The result already holds [9, 5, 3].","prompt":"The equal-to-pivot scan runs next.","options":[{"id":"equal-after-below","label":"Right after [9, 5, 3], giving [9, 5, 3, 10, 10]","rationale":"The equal scan runs after the below scan, so its appends extend the result on the right.","isCorrect":true},{"id":"equal-front","label":"At the front, pushing 9, 5, 3 back","rationale":"Appending adds to the end. The below band stays where it was first written.","isCorrect":false},{"id":"equal-merged","label":"Mixed in among 9, 5, 3 wherever a 10 was scanned","rationale":"The 10s are a separate scan over the input, so they cannot interleave with the below band.","isCorrect":false}],"answer":"The equal scan appends after the below band: [9, 5, 3, 10, 10]."},{"id":"above-scan","title":"What does the third scan leave in the result?","summary":"Above 10, nums holds 12 at index 1 and 14 at index 4.","prompt":"The above-pivot scan finishes the build.","options":[{"id":"above-correct","label":"[9, 5, 3, 10, 10, 12, 14]","rationale":"12 and 14 append after the pivot band in input order, completing the three stacked bands.","isCorrect":true},{"id":"above-sorted-whole","label":"[3, 5, 9, 10, 10, 12, 14]","rationale":"That sorts the whole array. The below band has to still read 9, 5, 3.","isCorrect":false},{"id":"above-before-equal","label":"[9, 5, 3, 12, 14, 10, 10]","rationale":"The above scan runs last, so 12 and 14 land behind the pivot band.","isCorrect":false}],"answer":"Below, then equal, then above, the result finishes as [9, 5, 3, 10, 10, 12, 14]."}]},{"id":"collapse-bands-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could one scan handle below and equal together?","summary":"Below and equal both come before the above band, so one scan could keep everything at or below the pivot and a second scan could keep the rest. That drops a pass over the array.","workspacePanel":"trace","pitfall":"The code below appends every value at or below the pivot in one scan, then every value above it.","whyItMatters":"A combined scan interleaves the pivot values among the below values wherever they were read, so the equal band no longer sits as one block after the below band. Keep the below and equal scans separate so each band is contiguous.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\nfor num in nums:\n    if num <= pivot:\n        result.append(num)\nfor num in nums:\n    if num > pivot:\n        result.append(num)\nreturn result","steps":[{"id":"first-below","title":"The combined scan starts","codeLine":4,"summary":"nums = [9, 12, 5, 10, 14, 3, 10], pivot = 10. 9 is at or below 10, so it is appended.","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":0},{"name":"result","values":[9]}],"pivot":10}},{"id":"pivot-too-early","title":"A 10 slips in among the below values","codeLine":4,"summary":"The scan reaches the first 10 at index 3. Since 10 <= 10, it is appended right after 5, before 3.","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":3},{"name":"result","values":[9,5,10]}],"pivot":10}},{"id":"second-pivot-early","title":"The second 10 lands mid-band too","codeLine":4,"summary":"After 3, the last 10 is appended. The result so far is [9, 5, 10, 3, 10], pivots scattered through the below values.","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":6},{"name":"result","values":[9,5,10,3,10]}],"pivot":10}},{"id":"wrong-order","title":"The equal band is no longer a block","codeLine":7,"summary":"The above scan adds 12, 14: [9, 5, 10, 3, 10, 12, 14]. The 10s sit inside the below values instead of after them.","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":4},{"name":"result","values":[9,5,10,3,10,12,14]}],"pivot":10}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nfor (const num of nums) {\n    if (num <= pivot) {\n        result.push(num);\n    }\n}\nfor (const num of nums) {\n    if (num > pivot) {\n        result.push(num);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":9,"8":12},"statementBundles":{"4":{"startLine":4,"endLine":6},"7":{"startLine":9,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<number> = [];\nfor (const num of nums) {\n    if (num <= pivot) {\n        result.push(num);\n    }\n}\nfor (const num of nums) {\n    if (num > pivot) {\n        result.push(num);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":9,"8":12},"statementBundles":{"4":{"startLine":4,"endLine":6},"7":{"startLine":9,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> result = new ArrayList<>();\nfor (Integer num : nums) {\n    if (num <= pivot) {\n        result.add(num);\n    }\n}\nfor (Integer num : nums) {\n    if (num > pivot) {\n        result.add(num);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":9,"8":12},"statementBundles":{"4":{"startLine":4,"endLine":6},"7":{"startLine":9,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> result = new();\nforeach (int num in nums) {\n    if (num <= pivot) {\n        result.Add(num);\n    }\n}\nforeach (int num in nums) {\n    if (num > pivot) {\n        result.Add(num);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":9,"8":12},"statementBundles":{"4":{"startLine":4,"endLine":6},"7":{"startLine":9,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> result;\nfor (int num : nums) {\n    if (num <= pivot) {\n        result.push_back(num);\n    }\n}\nfor (int num : nums) {\n    if (num > pivot) {\n        result.push_back(num);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":9,"8":12},"statementBundles":{"4":{"startLine":4,"endLine":6},"7":{"startLine":9,"endLine":11}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"Three inputs to run the three scans against.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":6},{"name":"result","values":[9,5,3,10,10]}],"pivot":10}}]},"body":["An array where every value equals the pivot, an array whose values all sit on one side of it, and an array holding a negative value."]},{"id":"all-equal-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"When every value equals the pivot, what does the below scan append?","workspacePanel":"visualizer","summary":"nums = [1, 1, 1], pivot = 1. The below scan runs first.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-equal-state","state":{"arrays":[{"name":"nums","values":[1,1,1],"i":0},{"name":"result","values":[]}],"pivot":1}}]},"options":[{"id":"appends-nothing","label":"Nothing, because no value is strictly below 1","rationale":"The below comparison fails for every value, so the below band is empty and the three 1s land in the equal scan, in order.","isCorrect":true},{"id":"appends-all","label":"All three 1s, since they are not above the pivot","rationale":"That is the at-or-below mistake. The below scan tests strictly less than, so a value equal to the pivot is skipped.","isCorrect":false},{"id":"needs-guard","label":"It errors, because the below band cannot be empty","rationale":"An empty band is fine: a scan that matches nothing simply appends nothing and the next scan continues.","isCorrect":false}],"answer":"The below scan appends nothing, the equal scan appends [1, 1, 1] in order, and the above scan appends nothing."},{"id":"all-greater-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Every value is above the pivot. What does the result look like?","workspacePanel":"visualizer","summary":"nums = [5, 4, 3], pivot = 2. All three scans still run in turn.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-greater-state","state":{"arrays":[{"name":"nums","values":[5,4,3],"i":0},{"name":"result","values":[]}],"pivot":2}}]},"options":[{"id":"preserved","label":"[5, 4, 3], unchanged in order","rationale":"Only the above scan matches, and it appends 5, 4, 3 in input order, so the original order is preserved.","isCorrect":true},{"id":"sorted","label":"[3, 4, 5], because the above band gets sorted","rationale":"No band is ever sorted. The above scan appends in scan order, leaving 5, 4, 3.","isCorrect":false},{"id":"empty","label":"[], because the below and equal scans appended nothing","rationale":"Those two scans are empty, but the above scan still appends all three values.","isCorrect":false}],"answer":"The first two scans append nothing and the above scan appends [5, 4, 3], so the result keeps the input order."},{"id":"negative-values-probe","chapter":"Edge cases","kind":"info","eyebrow":"Rule out a special case","title":"Negative values need no special branch","summary":"One negative value, a positive pivot, and the same three scans.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"negative-state","state":{"arrays":[{"name":"nums","values":[-3,4,3,2],"i":0},{"name":"result","values":[-3,2,4,3]}],"pivot":2}}]},"body":["The checks -3 < 2, then 2 == 2, then 4 > 2 and 3 > 2 read exactly as they do for positive values, so the scans build [-3, 2, 4, 3] without any test on sign."]},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Three scans over nums, run in band order.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"arrays":[{"name":"nums","values":[9,12,5,10,14,3,10],"i":0},{"name":"result","values":[]}],"pivot":10}}]},"body":["Start an empty result, then scan the array three times: collect the values below the pivot, then the values equal to it, then the values above it, appending each as you reach it. Return the result."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the three stable scans","summary":"Append the below-pivot values, then the equal ones, then the above ones, into a single result and return it.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"One comparison per value decides its band, and scan order keeps each band stable for free.","workspacePanel":"code","body":["The grouping this problem asks for is decided entirely by the pivot, and the order inside each group is decided entirely by the input.","Three scans, each appending in input order, place every value with a single comparison and keep the bands stable, all in O(n)."],"takeaways":[{"title":"One comparison names the band","body":"Each value needs only below, equal, or above the pivot, so no value is ever compared to another value."},{"title":"Scan order is the stability","body":"Appending values as the scan reaches them records input order directly, so the bands stay stable with no sorting."},{"title":"Three scans beat one sort","body":"Three linear passes are O(n), down from the O(n log n) a comparison sort spends keeping an order it was already handed."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
