{"id":"relative-sort-array","title":"Relative Sort Array","difficulty":"easy","patterns":["sorting-linear"],"primaryConcept":"sorting-linear","concepts":["sorting-linear"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"two-arrays","primaryParam":"arr1","secondaryParam":"arr2","sizeMetric":"total-length","constraints":["non-negative","bounded-values"],"sizes":[8,16,32,64],"valueRange":{"min":0,"max":1000}},"description":"Given two arrays `arr1` and `arr2`, return `arr1` sorted so that values appearing in `arr2` come first and keep the order they have in `arr2`.\n\nValues not appearing in `arr2` should come afterward in ascending order.\n\nFor this TraceCode exercise, use the bounded value range `0..1000` to solve the problem in linear time. Do not comparison-sort `arr1`.","requiredComplexity":[{"metric":"time","bound":"O(n)","scope":"function","functions":["relativeSortArray"],"case":"worst","enforcement":"advisory","reason":"The solution scans arr1, arr2, and the fixed value range 0..1000, so the bounded-range pass is constant relative to input size."}],"examples":[{"input":"arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]","output":"[2,2,2,1,4,3,3,9,6,7,19]","explanation":"Values from arr2 appear first in arr2 order. The remaining values 7 and 19 are appended in ascending order."},{"input":"arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]","output":"[22,28,8,6,17,44]","explanation":"The four values named by arr2 come first, then 17 and 44 remain sorted."}],"constraints":[{"id":"1-len-arr1-len-arr2-1000","text":"1 <= len(arr1), len(arr2) <= 1000","check":[{"kind":"sizeRange","target":"arr1","measure":"arrayLength","min":1,"max":1000},{"kind":"sizeRange","target":"arr2","measure":"arrayLength","min":1,"max":1000}]},{"id":"0-arr1-i-arr2-i-1000","text":"0 <= arr1[i], arr2[i] <= 1000","check":[{"kind":"valueRange","target":"arr1","selector":"arrayItems","min":0,"max":1000},{"kind":"valueRange","target":"arr2","selector":"arrayItems","min":0,"max":1000}]},{"id":"all-values-in-arr2-are-distinct","text":"All values in arr2 are distinct","check":{"kind":"uniqueness","target":"arr2","selector":"items"}},{"id":"every-value-in-arr2-appears-in-arr1","text":"Every value in arr2 appears in arr1"}],"starterCode":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        # Your code here\n        pass","functionName":"relativeSortArray","testCases":[{"id":"1","input":{"arr1":[2,3,1,3,2,4,6,7,9,2,19],"arr2":[2,1,4,3,9,6]},"expected":[2,2,2,1,4,3,3,9,6,7,19],"description":"Classic sample with leftover values appended in ascending order."},{"id":"2","input":{"arr1":[28,6,22,8,44,17],"arr2":[22,28,8,6]},"expected":[22,28,8,6,17,44],"description":"All priority values appear once and leftovers sort afterward."},{"id":"3","input":{"arr1":[5,5,5,1,1,3],"arr2":[1,5]},"expected":[1,1,5,5,5,3],"description":"Duplicate priority values should all be emitted together."},{"id":"4","input":{"arr1":[0,1000,500,0,3],"arr2":[1000,0]},"expected":[1000,0,0,3,500],"description":"The bounded scan must include both ends of the 0..1000 range."},{"id":"5","input":{"arr1":[4,3,2,1],"arr2":[4,3,2,1]},"expected":[4,3,2,1],"description":"When arr2 covers every value, the output follows arr2 exactly."},{"id":"hidden-1","input":{"arr1":[10,7,10,3,8,7,1],"arr2":[7,10]},"expected":[7,7,10,10,1,3,8],"description":"Several leftover values must be emitted in numeric order."},{"id":"hidden-2","input":{"arr1":[2,2,2,2],"arr2":[2]},"expected":[2,2,2,2],"description":"A single priority value consumes the entire array."},{"id":"hidden-3","input":{"arr1":[9,1,6,2,6,0,9,3],"arr2":[6,9,1]},"expected":[6,6,9,9,1,0,2,3],"description":"Leftover values below and between priority values still sort at the end."},{"id":"hidden-4","input":{"arr1":[1000,999,998,997],"arr2":[998]},"expected":[998,997,999,1000],"description":"Large bounded values should be ordered by the range scan."},{"id":"hidden-5","input":{"arr1":[4,1,4,6,6,2,1,5],"arr2":[6,4,1]},"expected":[6,6,4,4,1,1,2,5],"description":"Multiple duplicated priority groups are followed by sorted leftovers."}],"hints":[{"level":1,"content":"You only need to know how many times each value appears in arr1."},{"level":2,"content":"Emit every value from arr2 according to its count, then set that count to zero so it is not emitted again."},{"level":3,"content":"Scan values from 0 through 1000 and append any counts that remain. This replaces comparison sorting with a bounded counting pass.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"How should we produce arr2 values first and then sort the rest?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"custom-comparator","name":"Custom comparator sort","summary":"Sort arr1 using arr2 positions as ranks and numeric value as a fallback.","decisionReason":"It compares pairs of arr1 elements over and over, even though the bounded 0-to-1000 value range lets us count each value once and sweep, skipping the comparisons entirely.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Runs in O(n log n) time and uses O(n) space."],"isOptimal":false},{"id":"counting-range","name":"Frequency table and bounded scan","summary":"Count each value, emit arr2 groups in priority order, then scan values 0 through 1000 for leftovers.","decisionReason":"counts[value] records how many copies of each 0..1000 value appear in arr1. Emitting arr2 values from that table first, then sweeping the bounded range for leftovers, produces the required order without comparisons.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":true},{"id":"nested-search","name":"Repeatedly search arr1","summary":"For each value in arr2, scan arr1 to find matching values.","decisionReason":"This is the baseline already traced: it re-walks all of arr1 for every value arr2 names, so the passes multiply into O(n * m) instead of adding.","complexity":{"time":"O(n * m)","space":"O(n)"},"tradeoffs":["Runs in O(n * m) time and uses O(n) space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-counts","title":"Create the frequency table","description":"Initialize a keyed frequency structure for values from arr1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"initializes_keyed_state","scope":"init-frequency-map","readMode":"keyed-state-value-query-v1"}]},"semanticSpec":{"intent":"Create a mutable frequency structure that will map each value to its count.","doneWhen":"This step is done when the function initializes an empty keyed state before scanning arr1.","shouldFailWhen":"This step should fail if no keyed count structure exists or if it is created after the counting loop.","roles":["frequency table","arr1 value","count"],"mustProve":["The code creates a keyed state for counts.","The keyed state exists before values from arr1 are counted."],"mustNotAccept":["Sorting arr1 instead of counting values.","Using a fixed output array with hard-coded values."],"equivalentVariants":["Use a dictionary or map keyed by value.","Use another mutable keyed frequency structure."],"proofSnippets":[{"id":"py-relative-sort-init-counts","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        return []"}]},"commonMistakes":["Trying to sort arr1 before deciding the arr2 priority order","Creating counts inside the arr2 loop and losing frequencies"],"hint":"Start with a structure where counts[value] will mean how many times value appears in arr1."},{"id":"count-arr1","title":"Count every value in arr1","description":"Scan arr1 and increment the frequency for each value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"counts_items_by_key","scope":"count-frequencies","readMode":"keyed-state-value-query-v1"}]},"semanticSpec":{"intent":"Record the multiplicity of each value in arr1.","doneWhen":"This step is done when the code loops over arr1 and adds one to the count for the current value.","shouldFailWhen":"This step should fail if duplicate values overwrite each other or if the scan does not use arr1 values as keys.","roles":["arr1","current value","frequency update"],"mustProve":["The code scans arr1.","The code increments the count keyed by the scanned value."],"mustNotAccept":["Assigning every count to 1 and losing duplicates.","Counting arr2 instead of arr1."],"equivalentVariants":["Use counts[value] = counts.get(value, 0) + 1.","Use any equivalent map counter update."],"proofSnippets":[{"id":"py-relative-sort-count-arr1","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        for value in arr1:\n            counts[value] = counts.get(value, 0) + 1\n        return []"}]},"commonMistakes":["Using arr2 as the counted array","Overwriting counts instead of incrementing them"],"hint":"Duplicates matter, so each occurrence in arr1 must add one to its count."},{"id":"init-result","title":"Start the output array","description":"Create the result array after counts are available.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Prepare a mutable output sequence for the reconstructed order.","doneWhen":"This step is done when the code initializes an empty result sequence after the frequency count is built.","shouldFailWhen":"This step should fail if output is not accumulated in a sequence or if the result is never populated.","roles":["result array","frequency table","output construction"],"mustProve":["The code initializes a result sequence.","The result sequence is distinct from the input arrays."],"mustNotAccept":["Mutating arr2 and returning it.","Returning a fixed literal instead of building an output."],"equivalentVariants":["Use an empty list.","Use another mutable sequence that values are appended to."],"proofSnippets":[{"id":"py-relative-sort-init-result","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        for value in arr1:\n            counts[value] = counts.get(value, 0) + 1\n        result = []\n        return []"}]},"commonMistakes":["Appending into arr2 and destroying the priority order list","Initializing the result inside a loop so previous output is lost"],"hint":"After counting, create the output sequence you will append values into."},{"id":"append-counted-values","title":"Append values by their counts","description":"Use counts to append each priority value, then append remaining values during the bounded scan.","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"}]},"semanticSpec":{"intent":"Append scanned values into the result according to their recorded counts.","doneWhen":"This step is done when the code appends each repeated value into the result sequence using the count table.","shouldFailWhen":"This step should fail if values are not appended to the result or if counts are ignored.","roles":["priority value","leftover value","result append"],"mustProve":["The code appends a scanned value into the result sequence.","The append happens after the frequency table has been populated."],"mustNotAccept":["Appending each distinct value only once.","Returning counts instead of reconstructed values."],"equivalentVariants":["Use repeated append calls driven by counts.","Use an extend operation with repeated values when supported."],"proofSnippets":[{"id":"py-relative-sort-append-counted-values","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        for value in arr1:\n            counts[value] = counts.get(value, 0) + 1\n        result = []\n        for value in arr2:\n            for _ in range(counts.get(value, 0)):\n                result.append(value)\n            counts[value] = 0\n        return []"}]},"commonMistakes":["Appending a priority value just once even when its count is larger","Forgetting to zero a priority value before the leftover pass"],"hint":"For each value, the count says exactly how many copies to append."},{"id":"return-result","title":"Return the rebuilt array","description":"Return the result after priority values and sorted leftovers have been appended.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the reconstructed sequence after both output phases complete.","doneWhen":"This step is done when the function returns the same result sequence that received appended values.","shouldFailWhen":"This step should fail if the code returns the count table, arr2, or a constant instead of the rebuilt array.","roles":["result array","priority output","leftover output"],"mustProve":["The code returns the populated result sequence.","The returned sequence is produced by append operations."],"mustNotAccept":["Returning arr1 after an unsupported comparison sort.","Returning the frequency map."],"equivalentVariants":["Return the list used for all appends.","Return an equivalent output sequence after construction."],"proofSnippets":[{"id":"py-relative-sort-return-result","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        for value in arr1:\n            counts[value] = counts.get(value, 0) + 1\n        result = []\n        for value in arr2:\n            for _ in range(counts.get(value, 0)):\n                result.append(value)\n            counts[value] = 0\n        for value in range(1001):\n            for _ in range(counts.get(value, 0)):\n                result.append(value)\n        return result"}]},"commonMistakes":["Returning the count table instead of the rebuilt array","Forgetting the leftover bounded scan before returning"],"hint":"The final answer is the sequence you appended into."}],"slides":[{"id":"read-the-signal","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Order arr1 by arr2, then sort the rest","workspacePanel":"problem","body":["You get two arrays. Return arr1 reordered so that every value listed in arr2 comes first, in the exact order arr2 lists them; any value in arr1 that arr2 never names comes afterward in ascending order.","Values run from 0 to 1000. The obvious way leans on arr2 directly: for each value arr2 names, walk arr1 and pull every copy. Watch it run."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Scan arr1 once per value in arr2","summary":"It builds the priority section correctly, but every value in arr2 pays for its own full walk of arr1.","workspacePanel":"trace","body":["For each value arr2 names, scan all of arr1 and append every copy that matches. Then sort whatever arr1 values were left untouched and append those."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\nused = [False] * len(arr1)\nfor value in arr2:\n    for k in range(len(arr1)):\n        if arr1[k] == value:\n            result.append(arr1[k])\n            used[k] = True\nleftover = sorted(arr1[k] for k in range(len(arr1)) if not used[k])\nreturn result + leftover","steps":[{"id":"scan-for-2","title":"arr2 names 2, so walk all of arr1 for it","codeLine":4,"summary":"value is 2, the first entry in arr2. Sweep every index of arr1 and append each 2; three copies land in result.","state":{"nums":[2,3,1,3,2,4,6,7,9,2,19],"current":0,"labels":{"nums":"arr1"}}},{"id":"scan-for-1","title":"arr2 names 1, so walk all of arr1 again","codeLine":4,"summary":"value is now 1. arr1 is swept end to end a second time to find the single 1.","state":{"nums":[2,3,1,3,2,4,6,7,9,2,19],"current":2,"labels":{"nums":"arr1"}}},{"id":"scan-for-4","title":"Every later arr2 value repeats the full walk","codeLine":4,"summary":"value is 4. Each of arr2's six values triggers its own pass over all eleven arr1 elements.","state":{"nums":[2,3,1,3,2,4,6,7,9,2,19],"current":5,"labels":{"nums":"arr1"}}},{"id":"done","title":"Priority done, leftovers sorted and appended","codeLine":8,"summary":"After six full scans the priority section is [2,2,2,1,4,3,3,9,6]; the untouched 7 and 19 are sorted and appended to give [2,2,2,1,4,3,3,9,6,7,19].","state":{"arrays":[{"name":"result","values":[2,2,2,1,4,3,3,9,6,7,19]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nconst used = Array(arr1.length).fill(false);\nfor (const value of arr2) {\n    for (let k = 0; k < arr1.length; k++) {\n        if (arr1[k] === value) {\n            result.push(arr1[k]);\n            used[k] = true;\n        }\n    }\n}\nconst leftover = [...Array.from({ length: arr1.length }, (_, index) => index).filter((k) => !used[k]).map((k) => arr1[k])].sort((a, b) => a - b);\nreturn result.concat(leftover);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":11,"9":12},"statementBundles":{"7":{"startLine":7,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<number> = [];\nconst used = Array(arr1.length).fill(false);\nfor (const value of arr2) {\n    for (let k = 0; k < arr1.length; k++) {\n        if (arr1[k] === value) {\n            result.push(arr1[k]);\n            used[k] = true;\n        }\n    }\n}\nconst leftover = [...Array.from({ length: arr1.length }, (_, index) => index).filter((k) => !used[k]).map((k) => arr1[k])].sort((a, b) => a - b);\nreturn result.concat(leftover);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":11,"9":12},"statementBundles":{"7":{"startLine":7,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> result = new ArrayList<>();\nList<Boolean> used = new ArrayList<>();\nfor (int index = 0; index < arr1.size(); index++) {\n    used.add(false);\n}\nfor (Integer value : arr2) {\n    for (int k = 0; k < arr1.size(); k++) {\n        if (arr1.get(k) == value) {\n            result.add(arr1.get(k));\n            used.set(k, true);\n        }\n    }\n}\nList<Integer> leftover = new ArrayList<>();\nfor (int k = 0; k < arr1.size(); k++) {\n    if (!used.get(k)) {\n        leftover.add(arr1.get(k));\n    }\n}\nCollections.sort(leftover);\nList<Integer> result1 = new ArrayList<>(result);\nresult1.addAll(leftover);\nreturn result1;","lineMap":{"1":1,"2":2,"3":6,"4":7,"5":8,"6":9,"7":10,"8":14,"9":21},"statementBundles":{"2":{"startLine":2,"endLine":5},"7":{"startLine":10,"endLine":13},"8":{"startLine":14,"endLine":20},"9":{"startLine":21,"endLine":23}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> result = new();\nList<bool> used = Enumerable.Repeat<bool>(false, arr1.Count).ToList();\nforeach (int value in arr2) {\n    for (int k = 0; k < arr1.Count; k++) {\n        if (arr1[k] == value) {\n            result.Add(arr1[k]);\n            used[k] = true;\n        }\n    }\n}\nList<int> leftover = Enumerable.Range(0, arr1.Count).Where(k => !used[k]).Select(k => arr1[k]).ToList().OrderBy(value => value).ToList();\nreturn result.Concat(leftover).ToList();","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":11,"9":12},"statementBundles":{"7":{"startLine":7,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> result;\nvector<bool> used = vector<bool>(arr1.size(), false);\nfor (int value : arr2) {\n    for (int k = 0; k < arr1.size(); k++) {\n        if (arr1[k] == value) {\n            result.push_back(arr1[k]);\n            used[k] = true;\n        }\n    }\n}\nvector<int> leftover;\nfor (int k = 0; k < arr1.size(); k++) {\n    if (!used[k]) {\n        leftover.push_back(arr1[k]);\n    }\n}\nstable_sort(leftover.begin(), leftover.end());\nvector<int> result1 = result;\nresult1.insert(result1.end(), leftover.begin(), leftover.end());\nreturn result1;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":11,"9":18},"statementBundles":{"7":{"startLine":7,"endLine":10},"8":{"startLine":11,"endLine":17},"9":{"startLine":18,"endLine":20}}}}}},{"id":"cost-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the cost","title":"How does scanning arr1 once per arr2 value scale?","workspacePanel":"visualizer","summary":"arr2 has 6 values and arr1 has 11; now stretch both toward their limit of 1000 each.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cost-state","state":{"arrays":[{"name":"arr2 (one pass each)","values":[2,1,4,3,9,6],"current":3},{"name":"arr1 (re-walked every pass)","values":[2,3,1,3,2,4,6,7,9,2,19],"current":5}],"arr2_passes_done":"4 of 6","arr1_steps_per_pass":11,"steps_so_far":"4 x 11 = 44","work_formula":"len(arr2) x len(arr1)"}}]},"options":[{"id":"product","label":"About a million steps, the length of arr2 times the length of arr1","rationale":"Each value in arr2 walks all of arr1, so the work is len(arr2) times len(arr1). At 1000 and 1000 that is around 1,000,000 steps.","isCorrect":true},{"id":"linear","label":"About a thousand steps, one per element of arr1","rationale":"A single pass would be linear, but arr1 is rescanned once for every value arr2 names, so the passes multiply rather than add.","isCorrect":false},{"id":"logn","label":"About ten steps, since each value is found by halving","rationale":"Halving needs sorted data and a single target. Here every value triggers a fresh linear walk of arr1, with no halving anywhere.","isCorrect":false}],"answer":"Around a million, len(arr2) times len(arr1). Each value arr2 names re-walks all of arr1, so two arrays near 1000 elements multiply into roughly a million steps, even though every value already fits in the tiny range 0 to 1000."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"Which question retires the repeated scans?","workspacePanel":"visualizer","quiz":{"contract":"pattern-recognition-v1","question":"Which question, answered in one pass, would replace re-walking arr1 for every value?","signalPrompt":"Every value sits between 0 and 1000, a small fixed line. Pick the question that line lets you answer once and reuse.","options":[{"id":"sorting-linear","label":"How many times does each value appear in arr1?","signal":"Values fit on a bounded line, so one pass can tally every value's count and never scan arr1 again.","rationale":"With a count per value, the priority section reads each arr2 value's tally and the leftovers fall out of a single sweep of the line, no rescanning.","isCorrect":true},{"id":"sorting-basics","label":"Which value is smaller when two are compared?","signal":"A custom comparator can rank arr1 by arr2 position, but comparing pairs is the work the bounded range lets us skip.","rationale":"A comparator sort costs O(n log n) and compares values that the bounded range could instead just tally in one pass.","isCorrect":false},{"id":"two-pointers","label":"Where do two converging ends of a sorted array meet?","signal":"Two pointers merge or partition sorted data, but neither array here is sorted and the output order is arr2's, not numeric.","rationale":"There is nothing sorted to walk inward on, and the priority order comes from arr2, so two pointers have no boundary to sweep.","isCorrect":false},{"id":"binary-search","label":"Where does a single threshold fall in a sorted range?","signal":"Binary search narrows toward one boundary in a monotonic range.","rationale":"There is no single threshold to find; the task emits every value in a custom order, not one cutoff.","isCorrect":false}],"missFeedback":"The bounded value line lets one tally answer how often each value appears, which both the arr2 priority section and the sorted leftovers can read.","hint":"The clue is not where a value sits in arr1; it is how many times each value on the 0-to-1000 line appears."},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-counts","state":{"nums":[2,3,1,3,2,4,6,7,9,2,19],"seen":{},"labels":{"nums":"arr1","seen":"counts"}}}]}},{"id":"rebuild-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Choose the move","title":"With every value counted, how do you place arr2's values first?","workspacePanel":"visualizer","summary":"These are the counts for arr1, and arr2 = [2,1,4,3,9,6] still fixes the priority order.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"counts-only","state":{"seen":{"1":1,"2":3,"3":2,"4":1,"6":1,"7":1,"9":1,"19":1},"labels":{"seen":"counts"}}}]},"options":[{"id":"walk-arr2","label":"Walk arr2 in order and emit each value its counted number of times","rationale":"arr2 already lists the priority order, so reading its values left to right and emitting each by its count writes 2,2,2 then 1, 4, 3,3, 9, 6 in exactly the order arr2 demands.","isCorrect":true},{"id":"sweep-all","label":"Sweep the value line 0 to 1000 and emit every counted value","rationale":"That emits values in numeric order, which is the rule for the leftovers, not for arr2's section. The priority values must follow arr2's listed order, not their numeric order.","isCorrect":false},{"id":"emit-arr2-once","label":"Emit each arr2 value a single time in arr2 order","rationale":"Emitting 2 once drops two of its three copies. The count is exactly how many times each value must be written.","isCorrect":false}],"answer":"Walk arr2 in its given order and emit each value its count of times. arr2 supplies the order and the counts supply the multiplicity, so the section rebuilds as [2,2,2,1,4,3,3,9,6]."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which record should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"nums":[2,3,1,3,2,4,6,7,9,2,19],"seen":{},"labels":{"nums":"arr1","seen":"counts"}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Count, place arr2's values, then sweep for the rest","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"nums":[2,3,1,3,2,4,6,7,9,2,19],"seen":{"1":1,"2":3,"3":2,"4":1,"6":1,"7":1,"9":1,"19":1},"labels":{"nums":"arr1","seen":"counts"}}}]},"body":["One pass over arr1 = [2,3,1,3,2,4,6,7,9,2,19] tallies every value: three 2s, two 3s, and one each of 1, 4, 6, 7, 9, 19.","Then arr2 = [2,1,4,3,9,6] drives the priority section, and a sweep of the 0-to-1000 line picks up whatever counts remain. At each beat, decide what gets written before you watch it."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the build","title":"Rebuild from the counts","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"emit-priority","state":{"seen":{"1":1,"2":3,"3":2,"4":1,"6":1,"7":1,"9":1,"19":1},"seenHighlight":2,"labels":{"seen":"counts"}}},{"id":"zero-priority","state":{"seen":{"1":0,"2":0,"3":0,"4":0,"6":0,"7":1,"9":0,"19":1},"arrays":[{"name":"result","values":[2,2,2,1,4,3,3,9,6]}],"labels":{"seen":"counts"}}},{"id":"sweep-leftover","state":{"seen":{"1":0,"2":0,"3":0,"4":0,"6":0,"7":1,"9":0,"19":1},"seenHighlight":7,"arrays":[{"name":"result","values":[2,2,2,1,4,3,3,9,6,7,19]}],"labels":{"seen":"counts"}}}]},"beats":[{"id":"emit-priority","title":"arr2 starts with 2. How many copies does result get?","summary":"The counts are tallied and result is still empty; arr2's first value is 2.","prompt":"counts[2] is 3, and 2 is the first value arr2 names.","options":[{"id":"three","label":"Three 2s, then move to arr2's next value","rationale":"The count of 2 is 3, so emitting 2 three times reproduces every copy from arr1 before moving on to 1.","isCorrect":true},{"id":"one","label":"One 2, since arr2 lists 2 a single time","rationale":"arr2 lists each value once, and the count sets the copies. 2 must be written three times.","isCorrect":false},{"id":"all-distinct","label":"Every distinct arr2 value at once, one copy each","rationale":"The section is built value by value in arr2 order, each emitted its full count, not one pass of single copies.","isCorrect":false}],"answer":"Three 2s. counts[2] is 3, so the priority value 2 is emitted three times before the walk advances to 1."},{"id":"zero-priority","title":"After emitting each arr2 value, why set its count to 0?","summary":"result now holds [2,2,2,1,4,3,3,9,6] and the leftover sweep is about to begin.","prompt":"The values arr2 named have all been emitted, and a sweep of the whole 0-to-1000 line comes next.","options":[{"id":"avoid-double","label":"So the leftover sweep does not emit them a second time","rationale":"The sweep visits every value with a nonzero count. Zeroing each emitted priority value leaves only the untouched 7 and 19 for the sweep to find.","isCorrect":true},{"id":"free-memory","label":"To free the table before the sweep runs","rationale":"Zeroing is not about memory; the entry stays. It marks the value as already emitted so the sweep skips it.","isCorrect":false},{"id":"sorting","label":"So the remaining counts end up in sorted order","rationale":"The numeric sweep supplies sorted order. Zeroing only prevents an already-placed value from being emitted again.","isCorrect":false}],"answer":"So the leftover sweep skips them. Every emitted priority value is zeroed, leaving only 7 and 19 with a count for the sweep to pick up."},{"id":"sweep-leftover","title":"The sweep climbs the line. Which leftovers does it append, in what order?","summary":"Every priority value is now zeroed; read the counts to see which values still carry a nonzero tally as the sweep walks 0, 1, 2, ... upward.","prompt":"The priority section is [2,2,2,1,4,3,3,9,6], and the sweep is climbing from 0. Check the counts panel for the values that survive the zeroing.","options":[{"id":"seven-then-19","label":"7, then 19, because the sweep reaches 7 before 19","rationale":"Climbing the line low to high reaches 7 before 19, so the leftovers append in ascending order: [..., 7, 19].","isCorrect":true},{"id":"19-then-7","label":"19, then 7, the order they appeared in arr1","rationale":"The leftovers follow the number line, not arr1's order. The sweep visits 7 before 19, so 7 comes first.","isCorrect":false},{"id":"all-1001","label":"Every value from 0 to 1000, each appended once","rationale":"Only values with a nonzero count are emitted. The sweep steps past 0 through 6 and 8 through 18 silently, appending just 7 and 19.","isCorrect":false}],"answer":"7 then 19. The sweep climbs the line in order, so the leftovers land ascending and the result completes as [2,2,2,1,4,3,3,9,6,7,19]."}]},{"id":"double-emit-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can the leftover sweep just run over the original counts?","workspacePanel":"trace","summary":"After the arr2 section is written, the leftover sweep walks 0 to 1000 emitting whatever still has a count. Leaving the counts exactly as the first pass tallied them looks harmless: the priority section came out right, and the sweep clearly handles the untouched values. Watch it finish on arr1 = [2,2,1], arr2 = [2], where 2 was already placed.","pitfall":"The code below builds the priority section, then sweeps the whole range without first clearing the counts of the values it just emitted. Follow what the sweep does when it reaches 2.","whyItMatters":"Without zeroing, every priority value still carries its full count when the sweep arrives, so the sweep emits it a second time. Here the two 2s land in the priority section and then again at value 2 in the sweep, giving [2,2,1,2,2] for a three-element input. Set each priority value's count to 0 right after emitting it, so the sweep finds only the values arr2 never named.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"counts = {}\nfor value in arr1:\n    counts[value] = counts.get(value, 0) + 1\nresult = []\nfor value in arr2:\n    for _ in range(counts.get(value, 0)):\n        result.append(value)\nfor value in range(1001):\n    for _ in range(counts.get(value, 0)):\n        result.append(value)\nreturn result","steps":[{"id":"counts-ready","title":"arr1 = [2,2,1], arr2 = [2]: counts are two 2s and one 1","codeLine":3,"summary":"The tally gives counts[2] = 2 and counts[1] = 1. The correct output is [2,2,1].","state":{"seen":{"1":1,"2":2},"labels":{"seen":"counts"}}},{"id":"priority-2","title":"arr2 names 2, so result gets two 2s","codeLine":6,"summary":"value is 2, counts[2] is 2, so result becomes [2,2]. The priority section is correct, but counts[2] is left at 2.","state":{"seen":{"1":1,"2":2},"seenHighlight":2,"arrays":[{"name":"result","values":[2,2]}],"labels":{"seen":"counts"}}},{"id":"sweep-1","title":"The sweep reaches 1 and appends it","codeLine":9,"summary":"At value 1 the sweep emits the single 1, so result is [2,2,1]. So far it matches the expected output.","state":{"seen":{"1":1,"2":2},"seenHighlight":1,"arrays":[{"name":"result","values":[2,2,1]}],"labels":{"seen":"counts"}}},{"id":"sweep-2-again","title":"The sweep reaches 2, whose count was never cleared","codeLine":9,"summary":"counts[2] is still 2, so the sweep emits two more 2s. result becomes [2,2,1,2,2], five values from a three-element input, with 2 duplicated.","state":{"seen":{"1":1,"2":2},"seenHighlight":2,"arrays":[{"name":"result","values":[2,2,1,2,2]}],"labels":{"seen":"counts"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const counts = new Map();\nfor (const value of arr1) {\n    counts.set(value, (counts.has(value) ? counts.get(value) : 0) + 1);\n}\nconst result = [];\nfor (const value of arr2) {\n    for (let i = 0; i < (counts.has(value) ? counts.get(value) : 0); i++) {\n        result.push(value);\n    }\n}\nfor (let value = 0; value < 1001; value++) {\n    for (let i = 0; i < (counts.has(value) ? counts.get(value) : 0); i++) {\n        result.push(value);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":16},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"10":{"startLine":13,"endLine":15}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const counts: Map<number, number> = new Map();\nfor (const value of arr1) {\n    counts.set(value, (counts.has(value) ? counts.get(value)! : 0) + 1);\n}\nconst result: Array<number> = [];\nfor (const value of arr2) {\n    for (let i = 0; i < (counts.has(value) ? counts.get(value)! : 0); i++) {\n        result.push(value);\n    }\n}\nfor (let value = 0; value < 1001; value++) {\n    for (let i = 0; i < (counts.has(value) ? counts.get(value)! : 0); i++) {\n        result.push(value);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":16},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"10":{"startLine":13,"endLine":15}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"Map<Integer, Integer> counts = new HashMap<Integer, Integer>();\nfor (Integer value : arr1) {\n    counts.put(value, (counts.getOrDefault(value, 0) + 1));\n}\nList<Integer> result = new ArrayList<>();\nfor (Integer value : arr2) {\n    for (int i = 0; i < counts.getOrDefault(value, 0); i++) {\n        result.add(value);\n    }\n}\nfor (int value = 0; value < 1001; value++) {\n    for (int i = 0; i < counts.getOrDefault(value, 0); i++) {\n        result.add(value);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":16},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"10":{"startLine":13,"endLine":15}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"Dictionary<int, int> counts = new();\nforeach (int value in arr1) {\n    counts[value] = (counts.ContainsKey(value) ? counts[value] : 0) + 1;\n}\nList<int> result = new();\nforeach (int value in arr2) {\n    for (int i = 0; i < (counts.ContainsKey(value) ? counts[value] : 0); i++) {\n        result.Add(value);\n    }\n}\nfor (int value = 0; value < 1001; value++) {\n    for (int i = 0; i < (counts.ContainsKey(value) ? counts[value] : 0); i++) {\n        result.Add(value);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":16},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"10":{"startLine":13,"endLine":15}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"unordered_map<int, int> counts;\nfor (int value : arr1) {\n    counts[value] += 1;\n}\nvector<int> result;\nfor (int value : arr2) {\n    for (int i = 0; i < (counts.count(value) ? counts.at(value) : 0); i++) {\n        result.push_back(value);\n    }\n}\nfor (int value = 0; value < 1001; value++) {\n    for (int i = 0; i < (counts.count(value) ? counts.at(value) : 0); i++) {\n        result.push_back(value);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":16},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"10":{"startLine":13,"endLine":15}},"alternateStyles":{"close-to-source":{"code":"unordered_map<int, int> counts;\nfor (int value : arr1) {\n    counts[value] += 1;\n}\nvector<int> result;\nfor (int value : arr2) {\n    for (int i = 0; i < ([&] { auto item = counts.find(value); return item != counts.end() ? item->second : 0; }()); i++) {\n        result.push_back(value);\n    }\n}\nfor (int value = 0; value < 1001; value++) {\n    for (int i = 0; i < ([&] { auto item = counts.find(value); return item != counts.end() ? item->second : 0; }()); i++) {\n        result.push_back(value);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":16},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"10":{"startLine":13,"endLine":15}}}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","summary":"The build handled the mixed arrays. Two cases are worth a check before coding: the endpoints of the value range, and arr2 listed out of numeric order.","ctaLabel":"Check edge cases","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[2,3,1,3,2,4,6,7,9,2,19],"labels":{"nums":"arr1"}}}]},"body":["Two inputs deserve a check: values sitting at the endpoints 0 and 1000, and an arr2 that is not in numeric order.","Trace each and decide what, if anything, the rule needs added to handle it."]},{"id":"endpoint-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"For arr1 = [1000,0,3], arr2 = [3], how far must the sweep run?","workspacePanel":"visualizer","summary":"Only 3 is a priority value, so after it is zeroed the leftovers are 0 and 1000, the two ends of the allowed range.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"endpoint-state","state":{"nums":[1000,0,3],"seen":{"0":1,"3":0,"1000":1},"labels":{"nums":"arr1","seen":"counts"}}}]},"options":[{"id":"zero-to-1000","label":"From 0 through 1000 inclusive, covering both endpoints","rationale":"0 is a leftover and 1000 can be one too, so the sweep must visit both ends. A range that stops at 999 or starts at 1 would drop a value.","isCorrect":true},{"id":"min-to-max","label":"From the smallest leftover to the largest, skipping fixed ends","rationale":"Tracking the actual min and max also works, but the bounded range is known to be 0 to 1000, so sweeping the full inclusive range is the simpler guarantee that no endpoint is missed.","isCorrect":false},{"id":"one-to-999","label":"From 1 through 999, since 0 and 1000 are unusual values","rationale":"0 and 1000 are valid values, not special cases. Skipping them would drop the 0 here and any 1000 leftover elsewhere.","isCorrect":false}],"answer":"From 0 through 1000 inclusive. Both endpoints are legal values, so the sweep must include 0 and 1000 or it silently drops a leftover sitting at an end."},{"id":"arr2-order-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"For arr2 = [9,1,5], does the priority section need sorting first?","workspacePanel":"visualizer","summary":"arr2 lists 9 before 1 before 5, which is not ascending.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"arr2-state","state":{"arrays":[{"name":"arr2","values":[9,1,5]}]}}]},"options":[{"id":"keep-order","label":"No, emit the priority values in arr2's given order","rationale":"arr2 defines the required order, so 9 must lead, then 1, then 5. Sorting arr2 would replace the requested order with numeric order and produce the wrong answer.","isCorrect":true},{"id":"sort-arr2","label":"Yes, sort arr2 ascending before emitting","rationale":"Sorting arr2 to 1, 5, 9 throws away the very order the problem asks for. Only the leftovers are sorted, never arr2.","isCorrect":false},{"id":"sort-result","label":"Emit in any order, then sort the whole result at the end","rationale":"Sorting the whole result would put everything in numeric order and erase arr2's priority section entirely.","isCorrect":false}],"answer":"No sorting. arr2 is the priority order by definition, so emit 9, then 1, then 5 exactly as arr2 lists them; only the leftovers get sorted, and the sweep handles that."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"Tally arr1 by value, emit arr2's values in order and zero each as you go, then sweep 0 to 1000 for the rest.","ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[2,3,1,3,2,4,6,7,9,2,19],"seen":{},"labels":{"nums":"arr1","seen":"counts"}}}]},"body":["Walk arr1 once to tally how many times each value appears. Then walk arr2 in its given order, emitting each value as many times as it was counted, and clear that value's count once it is placed.","Finish by sweeping the value range from 0 to 1000, appending every value that still carries a count, and return what you collected."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the count-and-place sort","summary":"Build the output in three moves: count arr1, emit arr2 values by count, then sweep the leftovers in ascending order.","workspacePanel":"code","checkpoints":[{"id":"init-counts","title":"Create the frequency table","description":"Initialize a keyed frequency structure for values from arr1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"initializes_keyed_state","scope":"init-frequency-map","readMode":"keyed-state-value-query-v1"}]},"semanticSpec":{"intent":"Create a mutable frequency structure that will map each value to its count.","doneWhen":"This step is done when the function initializes an empty keyed state before scanning arr1.","shouldFailWhen":"This step should fail if no keyed count structure exists or if it is created after the counting loop.","roles":["frequency table","arr1 value","count"],"mustProve":["The code creates a keyed state for counts.","The keyed state exists before values from arr1 are counted."],"mustNotAccept":["Sorting arr1 instead of counting values.","Using a fixed output array with hard-coded values."],"equivalentVariants":["Use a dictionary or map keyed by value.","Use another mutable keyed frequency structure."],"proofSnippets":[{"id":"py-relative-sort-init-counts","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        return []"}]},"commonMistakes":["Trying to sort arr1 before deciding the arr2 priority order","Creating counts inside the arr2 loop and losing frequencies"],"hint":"Start with a structure where counts[value] will mean how many times value appears in arr1."},{"id":"count-arr1","title":"Count every value in arr1","description":"Scan arr1 and increment the frequency for each value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"counts_items_by_key","scope":"count-frequencies","readMode":"keyed-state-value-query-v1"}]},"semanticSpec":{"intent":"Record the multiplicity of each value in arr1.","doneWhen":"This step is done when the code loops over arr1 and adds one to the count for the current value.","shouldFailWhen":"This step should fail if duplicate values overwrite each other or if the scan does not use arr1 values as keys.","roles":["arr1","current value","frequency update"],"mustProve":["The code scans arr1.","The code increments the count keyed by the scanned value."],"mustNotAccept":["Assigning every count to 1 and losing duplicates.","Counting arr2 instead of arr1."],"equivalentVariants":["Use counts[value] = counts.get(value, 0) + 1.","Use any equivalent map counter update."],"proofSnippets":[{"id":"py-relative-sort-count-arr1","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        for value in arr1:\n            counts[value] = counts.get(value, 0) + 1\n        return []"}]},"commonMistakes":["Using arr2 as the counted array","Overwriting counts instead of incrementing them"],"hint":"Duplicates matter, so each occurrence in arr1 must add one to its count."},{"id":"init-result","title":"Start the output array","description":"Create the result array after counts are available.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Prepare a mutable output sequence for the reconstructed order.","doneWhen":"This step is done when the code initializes an empty result sequence after the frequency count is built.","shouldFailWhen":"This step should fail if output is not accumulated in a sequence or if the result is never populated.","roles":["result array","frequency table","output construction"],"mustProve":["The code initializes a result sequence.","The result sequence is distinct from the input arrays."],"mustNotAccept":["Mutating arr2 and returning it.","Returning a fixed literal instead of building an output."],"equivalentVariants":["Use an empty list.","Use another mutable sequence that values are appended to."],"proofSnippets":[{"id":"py-relative-sort-init-result","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        for value in arr1:\n            counts[value] = counts.get(value, 0) + 1\n        result = []\n        return []"}]},"commonMistakes":["Appending into arr2 and destroying the priority order list","Initializing the result inside a loop so previous output is lost"],"hint":"After counting, create the output sequence you will append values into."},{"id":"append-counted-values","title":"Append values by their counts","description":"Use counts to append each priority value, then append remaining values during the bounded scan.","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"}]},"semanticSpec":{"intent":"Append scanned values into the result according to their recorded counts.","doneWhen":"This step is done when the code appends each repeated value into the result sequence using the count table.","shouldFailWhen":"This step should fail if values are not appended to the result or if counts are ignored.","roles":["priority value","leftover value","result append"],"mustProve":["The code appends a scanned value into the result sequence.","The append happens after the frequency table has been populated."],"mustNotAccept":["Appending each distinct value only once.","Returning counts instead of reconstructed values."],"equivalentVariants":["Use repeated append calls driven by counts.","Use an extend operation with repeated values when supported."],"proofSnippets":[{"id":"py-relative-sort-append-counted-values","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        for value in arr1:\n            counts[value] = counts.get(value, 0) + 1\n        result = []\n        for value in arr2:\n            for _ in range(counts.get(value, 0)):\n                result.append(value)\n            counts[value] = 0\n        return []"}]},"commonMistakes":["Appending a priority value just once even when its count is larger","Forgetting to zero a priority value before the leftover pass"],"hint":"For each value, the count says exactly how many copies to append."},{"id":"return-result","title":"Return the rebuilt array","description":"Return the result after priority values and sorted leftovers have been appended.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the reconstructed sequence after both output phases complete.","doneWhen":"This step is done when the function returns the same result sequence that received appended values.","shouldFailWhen":"This step should fail if the code returns the count table, arr2, or a constant instead of the rebuilt array.","roles":["result array","priority output","leftover output"],"mustProve":["The code returns the populated result sequence.","The returned sequence is produced by append operations."],"mustNotAccept":["Returning arr1 after an unsupported comparison sort.","Returning the frequency map."],"equivalentVariants":["Return the list used for all appends.","Return an equivalent output sequence after construction."],"proofSnippets":[{"id":"py-relative-sort-return-result","language":"python","code":"class Solution:\n    def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:\n        counts = {}\n        for value in arr1:\n            counts[value] = counts.get(value, 0) + 1\n        result = []\n        for value in arr2:\n            for _ in range(counts.get(value, 0)):\n                result.append(value)\n            counts[value] = 0\n        for value in range(1001):\n            for _ in range(counts.get(value, 0)):\n                result.append(value)\n        return result"}]},"commonMistakes":["Returning the count table instead of the rebuilt array","Forgetting the leftover bounded scan before returning"],"hint":"The final answer is the sequence you appended into."}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","body":["Relative sort never re-scans arr1. One pass tallies each value, arr2 drives the priority section in its listed order, and a single sweep of the 0-to-1000 line emits whatever is left in ascending order.","It costs one pass over arr1, one over arr2, and one over the fixed range, so the work is O(n + R) with R = 1001 constant, down from the per-value rescan's O(n times m)."],"takeaways":[{"title":"Counts retire the rescans","body":"Tallying each value once lets both the arr2 section and the leftovers read from the same table, so arr1 is never walked again per value."},{"title":"arr2 orders, the sweep sorts","body":"The priority section follows arr2's listed order while the leftover sweep follows the number line, so two different orders come from one table."},{"title":"Zero what you place","body":"Clearing each priority value's count after emitting it is what keeps the leftover sweep from emitting those values a second time."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
