{"id":"sort-array-by-parity","title":"Sort Array by Parity","difficulty":"easy","patterns":["two-pointers"],"primaryConcept":"sorting-linear","concepts":["sorting-linear"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"array-length","valueRange":{"min":0,"max":100},"sizes":[8,16,32,64]},"description":"Given an integer array `nums`, return a new array with all even numbers first, followed by all odd numbers.\n\nKeep the relative order of the even numbers and the relative order of the odd numbers the same as in the original array.","examples":[{"input":"nums = [3,1,2,4]","output":"[2,4,3,1]","explanation":"The even values 2 and 4 come first in their original order, followed by the odd values 3 and 1."},{"input":"nums = [0,5,2,7,8]","output":"[0,2,8,5,7]","explanation":"All even values are emitted first, and each parity group remains stable."}],"constraints":[{"id":"1-len-nums-5000","text":"1 <= len(nums) <= 5000","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":5000}},{"id":"0-nums-i-5000","text":"0 <= nums[i] <= 5000","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":0,"max":5000}}],"starterCode":"class Solution:\n    def sortArrayByParity(self, nums: list[int]) -> list[int]:\n        # Your code here\n        pass","functionName":"sortArrayByParity","testCases":[{"id":"1","input":{"nums":[3,1,2,4]},"expected":[2,4,3,1],"description":"Mixed parity values from the canonical example."},{"id":"2","input":{"nums":[0,5,2,7,8]},"expected":[0,2,8,5,7],"description":"Zero is even, and both groups stay stable."},{"id":"3","input":{"nums":[2,4,6]},"expected":[2,4,6],"description":"All values are already even."},{"id":"4","input":{"nums":[9,7,5,3]},"expected":[9,7,5,3],"description":"All values are odd, so the output is unchanged."},{"id":"5","input":{"nums":[11,2,13,4,15,6]},"expected":[2,4,6,11,13,15],"description":"Alternating parity values exercise stable grouping."},{"id":"6","input":{"nums":[1]},"expected":[1],"description":"Single odd value."},{"id":"h1","input":{"nums":[10,12,1,14,3,16,5]},"expected":[10,12,14,16,1,3,5],"description":"Several evens before and after odds."},{"id":"h2","input":{"nums":[4,1,2,3,8,7,6]},"expected":[4,2,8,6,1,3,7],"description":"Stable even and odd order both matter."},{"id":"h3","input":{"nums":[1,0,1,0,1,0]},"expected":[0,0,0,1,1,1],"description":"Alternating parity values preserve relative order within each group."},{"id":"h4","input":{"nums":[5,4,3,2]},"expected":[4,2,5,3],"description":"Mixed positive values preserve stable parity order."}],"hints":[{"level":1,"content":"You only need two groups: even values, then odd values."},{"level":2,"content":"A stable partition appends matching values while scanning from left to right."},{"level":3,"content":"Scan once for evens, then scan once for odds, appending each matching value."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach keeps parity bands stable in linear time?","decisionPrompt":"Pick the one whose cost and order guarantee match the contract.","approaches":[{"id":"sort-by-parity-key","name":"Sort on a parity key","summary":"Give each value a key of 0 for even or 1 for odd, and sort the array on that key.","decisionReason":"It returns the right groups, but it compares values against each other to order bands that parity alone already settles.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Sorting keeps the bands together, but the value-to-value comparisons are work the answer never needed."],"isOptimal":false},{"id":"stable-two-pass","name":"Two stable scans","summary":"Scan once for even values, again for odd values, appending each in scan order.","decisionReason":"Each scan appends in input order, so both bands land stable in one linear pass each, O(n) total.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Two passes touch the array twice, but each is a single parity test and an append, no value-to-value ordering."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-result","title":"Initialize result","description":"Create the output sequence that will receive the even group and then the odd group.","commonMistakes":["Sorting `nums` in place and losing the within-band original order","Returning a count of even 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 parity-partitioned array.","shouldFailWhen":"This step should fail if there is no result sequence for collecting parity 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-sort-parity-init-result","language":"python","code":"class Solution:\n    def sortArrayByParity(self, nums: list[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 for parity.","commonMistakes":["Checking only the first value instead of every value","Scanning once and trying to place both 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 for parity.","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"],"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-sort-parity-scan-values","language":"python","code":"class Solution:\n    def sortArrayByParity(self, nums: list[int]) -> list[int]:\n        result = []\n        for num in nums:\n            if num % 2 == 0:\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 even, then odd order.","commonMistakes":["Appending odd values before the even values","Appending both bands in one pass so they interleave"],"hint":"Append each qualifying value as the scan reaches it.","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","parity 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 two passes, two temporary lists that are concatenated, or another stable append-based construction."],"proofSnippets":[{"id":"py-sort-parity-append-groups","language":"python","code":"class Solution:\n    def sortArrayByParity(self, nums: list[int]) -> list[int]:\n        result = []\n        for num in nums:\n            if num % 2 == 0:\n                result.append(num)\n        for num in nums:\n            if num % 2 == 1:\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 both bands have been appended.","commonMistakes":["Returning only the even-value band","Returning the original `nums` unchanged"],"hint":"The collected result is the final parity-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 a count of even or odd values.","Returning the input without building the result."],"equivalentVariants":["Return a concatenation of stable even and odd arrays if those arrays were built by scanning `nums`."],"proofSnippets":[{"id":"py-sort-parity-return-result","language":"python","code":"class Solution:\n    def sortArrayByParity(self, nums: list[int]) -> list[int]:\n        result = []\n        for num in nums:\n            if num % 2 == 0:\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":"Evens first, odds after, order kept","workspacePanel":"problem","body":["You are given an array. Return a new array where every even value comes first, then every odd value. Inside each of those two bands the values must stay in the order they had in the input.","The reflex is to reach for a sort. Watch a sort do it, and watch what it pays for."]},{"id":"sort-by-parity","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Sort the values by parity","summary":"Keying by parity and sorting lands on the right order, but it pays in comparisons between values to get there. Watch how much of that comparing the answer never actually needed.","workspacePanel":"trace","body":["Give each value a key of 0 if even or 1 if odd, then sort by swapping out-of-order neighbors."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def sortArrayByParity(nums: list[int]) -> list[int]:\n    def key(x: int) -> int:\n        return x % 2\n    result = list(nums)\n    for i in range(len(result)):\n        for j in range(len(result) - 1 - i):\n            if key(result[j]) > key(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 parity key","codeLine":3,"summary":"nums = [3, 1, 2, 8, 4]. Tag each value 0 for even or 1 for odd, then sort on the tag.","state":{"nums":[3,1,2,8,4]}},{"id":"sort-compares","title":"Neighbors are compared and swapped","codeLine":7,"summary":"1 has key 1 and 2 has key 0, so this adjacent pair is out of order and swaps. Sorting pits values against each other, pass after pass.","state":{"nums":[3,2,1,8,4],"i":1}},{"id":"sorted-out","title":"It lands on a right answer","codeLine":9,"summary":"Keying by parity floats evens ahead of odds, giving [2, 8, 4, 3, 1] here. Correct, after many value-to-value comparisons.","state":{"nums":[2,8,4,3,1]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function key(x) {\n    return floorModulo(x, 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 (key(result[j]) > key(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 key(x: number): number {\n    return floorModulo(x, 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 (key(result[j]) > key(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 Key(int x) {\n    return FloorModulo(x, 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 (Key(result[j]) > Key(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 key = [&]( int x ) -> int {\n    return floorModulo(x, 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 (key(result[j]) > key(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 key(int x) {\n    return Math.floorMod(x, 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 (key(result.get(j)) > key(result.get(j + 1))) {\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 checks pairs over several passes.","options":[{"id":"value-to-value","label":"Comparing one value against another value","rationale":"The band each value belongs to is fixed by its parity alone, so every comparison between two values is work the answer does not depend on.","isCorrect":true},{"id":"value-to-parity","label":"Testing each value for even or odd","rationale":"That test is exactly what the answer needs to know each value’s band. It is the useful work.","isCorrect":false},{"id":"recount-length","label":"Recounting the array length on every pass","rationale":"Repeated length reads are not where the cost comes from. The cost is the repeated value-against-value comparing as the passes run.","isCorrect":false}],"answer":"The bands are decided by parity, so pitting values against each other is wasted: the answer only needs each value tested for even or odd once."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"Which fact about each value, asked once, decides which band it goes in?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pattern-quiz-state","state":{"arrays":[{"name":"nums","values":[3,1,2,8,4],"i":0},{"name":"result","values":[]}]}}]},"quiz":{"contract":"pattern-recognition-v1","question":"Which fact about each value, asked once, decides which band it goes in?","signalPrompt":"Every value is either even or odd, and each group keeps its input order.","options":[{"id":"sorting-linear","label":"Whether the value is even or odd","signal":"One parity test per value sends it to a fixed band, with no value-to-value comparison.","rationale":"A single test names each value as even or odd, so the answer builds in two linear scans, not by ordering pairs.","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 band is decided by parity 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 value 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":"Parity alone decides the band; value ranks do not matter.","hint":"For each value the only question is even or odd."}},{"id":"order-is-free-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Find the rule","title":"If we append even values as we scan, what order does the even band end up in?","workspacePanel":"visualizer","summary":"In nums the even values are 2, 8, 4, at positions 2, 3, 4.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"order-is-free-state","state":{"arrays":[{"name":"nums","values":[3,1,2,8,4],"i":0},{"name":"result","values":[]}]}}]},"options":[{"id":"scan-order","label":"The order they were scanned: 2, 8, 4","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: 2, 4, 8","rationale":"Sorting within a band is the work we are trying to drop. The contract wants input order, not ascending order.","isCorrect":false},{"id":"reversed","label":"Reversed: 4, 8, 2","rationale":"A forward scan appends front to back, so the first even value scanned is the first appended. Nothing reverses it.","isCorrect":false}],"answer":"Append-as-you-scan writes 2, 8, 4 in that order, so the band is stable for free. No within-band comparison is ever needed."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which approach keeps parity bands stable in linear time?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"arrays":[{"name":"nums","values":[3,1,2,8,4]},{"name":"result","values":[2,8,4,3,1]}]}}]},"selection":{"contract":"approach-selection-v1","question":"Which approach keeps parity bands stable in linear time?","decisionPrompt":"Pick the one whose cost and order guarantee match the contract.","approaches":[{"id":"sort-by-parity-key","name":"Sort on a parity key","summary":"Give each value a key of 0 for even or 1 for odd, and sort the array on that key.","decisionReason":"It returns the right groups, but it compares values against each other to order bands that parity alone already settles.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Sorting keeps the bands together, but the value-to-value comparisons are work the answer never needed."],"isOptimal":false},{"id":"stable-two-pass","name":"Two stable scans","summary":"Scan once for even values, again for odd values, appending each in scan order.","decisionReason":"Each scan appends in input order, so both bands land stable in one linear pass each, O(n) total.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Two passes touch the array twice, but each is a single parity test 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, two scans to come","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"arrays":[{"name":"nums","values":[3,1,2,8,4],"i":0},{"name":"result","values":[]}]}}]},"body":["Take nums = [3, 1, 2, 8, 4] and an empty result.","Two scans run in turn: the first appends every even value, the second every odd value. Each scan appends in the order it reads."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the scans","title":"Build [2, 8, 4, 3, 1] in two scans","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"even-scan","state":{"arrays":[{"name":"nums","values":[3,1,2,8,4],"i":4},{"name":"result","values":[2,8,4]}]}},{"id":"odd-scan","state":{"arrays":[{"name":"nums","values":[3,1,2,8,4],"i":1},{"name":"result","values":[2,8,4,3,1]}]}},{"id":"done","state":{"arrays":[{"name":"nums","values":[3,1,2,8,4]},{"name":"result","values":[2,8,4,3,1]}]}}]},"beats":[{"id":"even-scan","title":"The first scan keeps only even values. What is the result so far?","summary":"The even scan has just walked the whole array.","prompt":"The even scan has just finished.","options":[{"id":"even-correct","label":"[2, 8, 4]","rationale":"2, 8, and 4 are the even values, appended in the order the scan reached them.","isCorrect":true},{"id":"even-sorted","label":"[2, 4, 8]","rationale":"That is the even band sorted. The scan appends in input order, so 8 comes before 4.","isCorrect":false},{"id":"even-with-odd","label":"[2, 8, 4, 3, 1]","rationale":"The odd values belong to the second scan. The first scan stops at even values.","isCorrect":false}],"answer":"The even scan produces [2, 8, 4], in the order they appeared."},{"id":"odd-scan","title":"The second scan appends the odd values. Where do they land?","summary":"The odd values, in input order, are 3 then 1. The result already holds [2, 8, 4].","prompt":"The odd scan runs next.","options":[{"id":"odd-after-even","label":"Right after [2, 8, 4], giving [2, 8, 4, 3, 1]","rationale":"The odd scan runs after the even scan, so its appends extend the result on the right, in input order.","isCorrect":true},{"id":"odd-front","label":"At the front, pushing 2, 8, 4 back","rationale":"Appending adds to the end. The even band stays where it was first written.","isCorrect":false},{"id":"odd-sorted","label":"After the evens, but sorted: [2, 8, 4, 1, 3]","rationale":"No band is ever sorted. The odd scan appends 3 then 1, the order they appeared.","isCorrect":false}],"answer":"The odd scan appends 3 then 1 after the even band: [2, 8, 4, 3, 1]."},{"id":"done","title":"After both scans, what is returned?","summary":"The even band sits ahead of the odd band, each in input order.","prompt":"The two scans have finished.","options":[{"id":"return-built","label":"[2, 8, 4, 3, 1], the result the two scans built","rationale":"Evens first in input order, then odds in input order, is exactly the contract, so the built result is returned.","isCorrect":true},{"id":"return-sorted","label":"[2, 4, 8, 1, 3], the array sorted within each band","rationale":"The bands keep input order, not ascending order. 8 stays ahead of 4 and 3 ahead of 1.","isCorrect":false},{"id":"return-input","label":"[3, 1, 2, 8, 4], the original array","rationale":"The original interleaves evens and odds. The scans grouped the evens ahead of the odds.","isCorrect":false}],"answer":"Even band, then odd band, each in input order: [2, 8, 4, 3, 1]. Two scans, no value-to-value comparison."}]},{"id":"one-pass-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Does it matter which scan runs first?","summary":"Two scans, one for each band, have to run in the same order the output requires. If the odd scan runs first and the even scan second, each value still lands in the result. Watch where the evens end up.","workspacePanel":"trace","pitfall":"The code below runs the odd scan first and the even scan second, each appending the values it matches.","whyItMatters":"The first scan fills the front of the result, so running the odd scan first puts the odd values ahead of every even value. Run the even scan first so every even value is appended before any odd value.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\nfor num in nums:\n    if num % 2 == 1:\n        result.append(num)\nfor num in nums:\n    if num % 2 == 0:\n        result.append(num)\nreturn result","steps":[{"id":"odd-first","title":"The odd scan runs first and appends 3","codeLine":4,"summary":"nums = [3, 2]. The odd scan tests each value: 3 is odd, so it is appended, and 2 is skipped. The result is [3].","state":{"arrays":[{"name":"nums","values":[3,2],"i":0},{"name":"result","values":[3]}]}},{"id":"even-second","title":"The even scan runs next and appends 2","codeLine":7,"summary":"The even scan now tests each value: 3 is skipped, 2 is even and is appended behind the 3. The result is [3, 2].","state":{"arrays":[{"name":"nums","values":[3,2],"i":1},{"name":"result","values":[3,2]}]}},{"id":"evens-last","title":"The even value ends up behind the odd one","codeLine":8,"summary":"The result is [3, 2], with the even value 2 trailing the odd value 3. The contract wants the evens first, [2, 3].","state":{"arrays":[{"name":"nums","values":[3,2]},{"name":"result","values":[3,2]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nfor (const num of nums) {\n    if (floorModulo(num, 2) === 1) {\n        result.push(num);\n    }\n}\nfor (const num of nums) {\n    if (floorModulo(num, 2) === 0) {\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 (floorModulo(num, 2) === 1) {\n        result.push(num);\n    }\n}\nfor (const num of nums) {\n    if (floorModulo(num, 2) === 0) {\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 (Math.floorMod(num, 2) == 1) {\n        result.add(num);\n    }\n}\nfor (Integer num : nums) {\n    if (Math.floorMod(num, 2) == 0) {\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 (FloorModulo(num, 2) == 1) {\n        result.Add(num);\n    }\n}\nforeach (int num in nums) {\n    if (FloorModulo(num, 2) == 0) {\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 (floorModulo(num, 2) == 1) {\n        result.push_back(num);\n    }\n}\nfor (int num : nums) {\n    if (floorModulo(num, 2) == 0) {\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":"An array with no odd values makes one scan append nothing. The value 0 also has to pick a band.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"arrays":[{"name":"nums","values":[3,1,2,8,4],"i":4},{"name":"result","values":[2,8,4]}]}}]},"body":["An array with no odd values, and the value 0.","If each scan only appends what matches its single parity test, both cases are already decided."]},{"id":"all-even-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"When every value is even, what does the odd scan append?","workspacePanel":"visualizer","summary":"nums = [2, 4, 6]. The even scan runs first, then the odd scan.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-even-state","state":{"arrays":[{"name":"nums","values":[2,4,6],"i":0},{"name":"result","values":[2,4,6]}]}}]},"options":[{"id":"appends-nothing","label":"Nothing: no value is odd, so the result is just the even band","rationale":"The odd test fails for every value, so the odd scan appends nothing and the result is [2, 4, 6] from the even scan.","isCorrect":true},{"id":"appends-all","label":"All three values again, doubling the result","rationale":"The odd scan tests for odd values; none of 2, 4, 6 is odd, so it appends nothing.","isCorrect":false},{"id":"needs-guard","label":"It errors, because the odd band cannot be empty","rationale":"An empty band is fine: a scan that matches nothing simply appends nothing and the result is already complete.","isCorrect":false}],"answer":"The even scan appends [2, 4, 6] and the odd scan appends nothing, so the result is [2, 4, 6] unchanged."},{"id":"zero-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"The value 0 is in the array. Which band does it land in?","workspacePanel":"visualizer","summary":"nums = [0, 5, 2]. The even scan tests each value with num % 2 == 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-state","state":{"arrays":[{"name":"nums","values":[0,5,2],"i":0},{"name":"result","values":[]}]}}]},"options":[{"id":"even-band","label":"The even band, first, giving [0, 2, 5]","rationale":"0 % 2 is 0, so the even scan appends 0 then 2, and the odd scan appends 5.","isCorrect":true},{"id":"dropped","label":"Neither band, because 0 is neither even nor odd","rationale":"0 % 2 is 0, so the even test matches and 0 is appended like any other even value.","isCorrect":false},{"id":"odd-band","label":"The odd band, after 5","rationale":"0 % 2 is 0, not 1, so the odd test fails and 0 joins the even band instead.","isCorrect":false}],"answer":"0 % 2 is 0, so the even scan appends 0 then 2 and the odd scan appends 5, giving [0, 2, 5]."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Two scans over one array, and the order they run in is the whole guarantee.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"arrays":[{"name":"nums","values":[3,1,2,8,4],"i":0},{"name":"result","values":[]}]}}]},"body":["Start an empty result, then scan the array twice: collect the even values, then the odd values, 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 two stable scans","summary":"Now turn the two scans into code: start an empty result, scan nums testing each value's parity, append the even matches and then the odd matches in scan order, and return the result you built.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"One parity test per value decides its band, and scan order keeps each band stable for free.","workspacePanel":"code","body":["The problem reads like a sort, but it never asks how values rank against each other, only whether each is even or odd.","Two scans, each appending in input order, place every value with a single parity test and keep the bands stable, all in O(n)."],"takeaways":[{"title":"One test names the band","body":"Each value needs only even or odd, 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":"Two scans beat one sort","body":"Two 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"},"starterFunctionName":"sortArrayByParity","tags":["Array","Stable Partition","Sorting"]}
