{"id":"counting-sort","title":"Counting Sort","difficulty":"medium","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":"array","primaryParam":"nums","sizeMetric":"length","sizes":[8,16,32,64],"valueRange":[-20,20]},"description":"Given an integer array `nums`, return a sorted copy of the array, smallest value first.\n\nEach value is bounded: every `nums[i]` lies between -10^4 and 10^4. For nums = [3, -1, 1, 3] the sorted copy is [-1, 1, 3, 3].","examples":[{"input":"nums = [5,3,1,2,3]","output":"[1,2,3,3,5]","explanation":"The value 3 appears twice, so it is emitted twice after 1 and 2."},{"input":"nums = [-2,5,0,-2,3]","output":"[-2,-2,0,3,5]","explanation":"Negative values are allowed, and the two -2s both appear at the front of the sorted copy."}],"constraints":[{"id":"0-len-nums-10-5","text":"0 <= len(nums) <= 10^5","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":0,"max":100000}},{"id":"10-4-nums-i-10-4","text":"-10^4 <= nums[i] <= 10^4","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-10000,"max":10000}},{"id":"the-value-range-max-nums-min-nums-is-bounded-for-the-intended-co","text":"The value range max(nums) - min(nums) is bounded for the intended counting-sort solution"}],"starterCode":"class Solution:\n    def countingSort(self, nums: list[int]) -> list[int]:\n        # Your code here\n        pass","functionName":"countingSort","testCases":[{"id":"1","input":{"nums":[5,3,1,2,3]},"expected":[1,2,3,3,5],"description":"Unsorted positive numbers with a duplicate."},{"id":"2","input":{"nums":[-2,5,0,-2,3]},"expected":[-2,-2,0,3,5],"description":"Negative and positive values."},{"id":"3","input":{"nums":[]},"expected":[],"description":"Empty input returns an empty sorted copy."},{"id":"4","input":{"nums":[4,4,4]},"expected":[4,4,4],"description":"All values are identical."},{"id":"5","input":{"nums":[10,-1,10,7,-1,0]},"expected":[-1,-1,0,7,10,10],"description":"Sparse bounded range with duplicate extremes."},{"id":"h1","input":{"nums":[3,1,2,2,0,-1]},"expected":[-1,0,1,2,2,3],"description":"Mixed signs with a duplicate."},{"id":"h2","input":{"nums":[10,-10,0,10]},"expected":[-10,0,10,10],"description":"A sparse range with repeated extremes."},{"id":"h3","input":{"nums":[5,4,3,2,1]},"expected":[1,2,3,4,5],"description":"Descending input should sort into ascending order."},{"id":"h4","input":{"nums":[2,-1,2,0,-1,3]},"expected":[-1,-1,0,2,2,3],"description":"Repeated negatives and positives."},{"id":"h5","input":{"nums":[7,7,7,7]},"expected":[7,7,7,7],"description":"Already sorted identical values stay unchanged."},{"id":"h6","input":{"nums":[-2,0,-2,3,1]},"expected":[-2,-2,0,1,3],"description":"An empty input remains empty."},{"id":"h7","input":{"nums":[-10000,10000,0,-10000]},"expected":[-10000,-10000,0,10000],"description":"Boundary values and duplicates are ordered together."}],"hints":[{"level":1,"content":"Count how many times each value appears before building the sorted output."},{"level":2,"content":"Track the smallest and largest values so you know which range to emit."},{"level":3,"content":"Scan values from min to max and append each value exactly count[value] times."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Choose the approach whose cost matches a bounded value range.","approaches":[{"id":"comparison-sort","name":"Compare and order","summary":"Sort the array by comparing each value against the others, the way the opener traced.","decisionReason":"Right answer, wrong cost: every position compares against the values past it, about n^2 comparisons, even though the bounded range never needs a single comparison.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["Runs in O(n^2) time and sorts in place."],"isOptimal":false},{"id":"counting-sort","name":"Count, then sweep the range","summary":"Tally each value, then walk the value range low to high emitting each value its count of times.","decisionReason":"The intended route: one pass tallies occurrences, one sweep of the bounded value line rebuilds sorted order without comparing anything.","complexity":{"time":"O(n + R)","space":"O(n + k)"},"tradeoffs":["Runs in O(n + R) time, sweeping the min-to-max range, and uses O(n + k) space for the result plus a count keyed by the k distinct values."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-counts","title":"Guard the empty input, then create the count table","description":"Return an empty copy when nums is empty, then initialize a keyed structure that will hold each value’s count.","commonMistakes":["Seeding min and max from the first value before checking for an empty input","Sorting nums first instead of building counts","Using a single number instead of a keyed table"],"hint":"Return [] up front when there is no first value, then make counts[value] mean how many times value appears.","semanticSpec":{"intent":"Return early on an empty input, then create the keyed count table before scanning.","doneWhen":"This step is done when an empty keyed count state exists before the input scan, with the empty input returned up front.","shouldFailWhen":"This step should fail if there is no reusable keyed count state, or the empty input is read before being guarded.","roles":["count table","input values"],"mustProve":["A keyed count state is initialized before frequency counting."],"mustNotAccept":["Calling a comparison sort instead of creating count state.","Seeding the range from the first value with no empty-input guard."],"equivalentVariants":["Use a dictionary or map keyed by value.","Use any equivalent keyed frequency structure."],"proofSnippets":[{"id":"py-counting-sort-init-counts","language":"python","code":"class Solution:\n    def countingSort(self, nums: list[int]) -> list[int]:\n        if not nums:\n            return []\n        counts = {}"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"initializes_keyed_state","scope":"init-frequency-map","readMode":"keyed-state-value-query-v1"}]}},{"id":"count-values","title":"Tally each value","description":"Scan nums and add one to the count for every value you pass.","commonMistakes":["Setting each count to 1 and losing duplicates","Tallying only the distinct values"],"hint":"Every occurrence adds one to its value’s count.","semanticSpec":{"intent":"Build value frequencies from one pass over the input.","doneWhen":"This step is done when the scan increments the keyed count for the current value.","shouldFailWhen":"This step should fail if duplicate values are not accumulated.","roles":["current value","count table"],"mustProve":["Each input value contributes to a keyed count update."],"mustNotAccept":["Assigning each count to a constant without preserving previous occurrences."],"equivalentVariants":["Use counts[num] = counts.get(num, 0) + 1.","Use any equivalent keyed counter update."],"proofSnippets":[{"id":"py-counting-sort-count-values","language":"python","code":"class Solution:\n    def countingSort(self, nums: list[int]) -> list[int]:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"counts_items_by_key","scope":"count-frequencies","readMode":"keyed-state-value-query-v1"}]}},{"id":"track-bounds","title":"Track the smallest and largest values","description":"While tallying, keep the minimum and maximum value seen so the sweep knows where to start and stop.","commonMistakes":["Hard-coding the sweep to start at 0, which drops negative values","Never recording the minimum and maximum, leaving the sweep without bounds"],"hint":"The sweep runs from min_val to max_val, so update both as each value is counted.","semanticSpec":{"intent":"Maintain the running minimum and maximum value across the input scan.","doneWhen":"This step is done when the smallest and largest values are tracked during the tally scan.","shouldFailWhen":"This step should fail if the sweep bounds are fixed instead of taken from the actual values.","roles":["current value","value bounds"],"mustProve":["The minimum and maximum values are maintained while scanning the input."],"mustNotAccept":["Sweeping from a constant lower bound that ignores negative values."],"equivalentVariants":["Update min_val and max_val inside the tally loop.","Use any equivalent running minimum and maximum over the input."],"proofSnippets":[{"id":"py-counting-sort-track-bounds","language":"python","code":"class Solution:\n    def countingSort(self, nums: list[int]) -> list[int]:\n        counts = {}\n        min_val = nums[0]\n        max_val = nums[0]\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n            if num < min_val:\n                min_val = num\n            if num > max_val:\n                max_val = num"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best","readMode":"numeric-state-value-query-v1"}]}},{"id":"emit-values","title":"Sweep the range and emit","description":"Walk the value range from the minimum to the maximum, appending each value its count of times.","commonMistakes":["Sweeping range(min_val, max_val), which stops one short and drops the maximum value","Appending each value only once and dropping duplicates","Walking the count table’s keys in their stored order instead of numeric order"],"hint":"Sorted order comes from sweeping values low to high, not from the order keys were stored.","semanticSpec":{"intent":"Append counted values into the result while sweeping the value range in order.","doneWhen":"This step is done when each swept value is appended into the result the number of times it was counted.","shouldFailWhen":"This step should fail if values are not appended to a result sequence.","roles":["result","value range","count"],"mustProve":["A scan state is appended into the result sequence."],"mustNotAccept":["Returning the count table directly."],"equivalentVariants":["Loop over range(min_val, max_val + 1) and append each present value count[value] times.","Use any equivalent ordered sweep that appends each value by its count."],"proofSnippets":[{"id":"py-counting-sort-emit-values","language":"python","code":"class Solution:\n    def countingSort(self, nums: list[int]) -> list[int]:\n        if not nums:\n            return []\n        counts = {}\n        min_val = nums[0]\n        max_val = nums[0]\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n            if num < min_val:\n                min_val = num\n            if num > max_val:\n                max_val = num\n        result = []\n        for value in range(min_val, max_val + 1):\n            if value in counts:\n                for _ in range(counts[value]):\n                    result.append(value)"},{"id":"js-counting-sort-emit-values","language":"javascript","code":"class Solution {\n  countingSort(nums) {\n    if (nums.length === 0) return [];\n    const counts = {};\n    let minVal = nums[0];\n    let maxVal = nums[0];\n    for (const num of nums) {\n      counts[num] = (counts[num] || 0) + 1;\n      if (num < minVal) minVal = num;\n      if (num > maxVal) maxVal = num;\n    }\n    const result = [];\n    for (let value = minVal; value <= maxVal; value++) {\n      if (value in counts) {\n        for (let i = 0; i < counts[value]; i++) {\n          result.push(value);\n        }\n      }\n    }\n  }\n}"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"appends_scan_state_to_result","scope":"counted-append-to-result","readMode":"array-scan-value-query-v1"}]}},{"id":"return-result","title":"Return the sorted copy","description":"Return the emitted result sequence.","commonMistakes":["Returning the count table","Returning nums unchanged"],"hint":"Return the rebuilt sorted values to the caller.","semanticSpec":{"intent":"Return the sorted result sequence after the sweep.","doneWhen":"This step is done when the terminal return is the populated result sequence.","shouldFailWhen":"This step should fail if the terminal return is not the result sequence.","roles":["result","terminal return"],"mustProve":["The result sequence is returned."],"mustNotAccept":["Returning the count table."],"equivalentVariants":["Return result.","Return any equivalent populated result sequence."],"proofSnippets":[{"id":"py-counting-sort-return-result","language":"python","code":"class Solution:\n    def countingSort(self, nums: list[int]) -> list[int]:\n        if not nums:\n            return []\n        counts = {}\n        min_val = nums[0]\n        max_val = nums[0]\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n            if num < min_val:\n                min_val = num\n            if num > max_val:\n                max_val = num\n        result = []\n        for value in range(min_val, max_val + 1):\n            if value in counts:\n                for _ in range(counts[value]):\n                    result.append(value)\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":"Return the values in sorted order","workspacePanel":"problem","body":["You get an integer array and must return a sorted copy of it, smallest value first. The values are bounded: each one sits between -10^4 and 10^4.","Every value lies inside a small fixed range. Counting how often each value appears can recover sorted order without comparing values against each other."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Compare values to order them","summary":"It sorts correctly, but each position runs a fresh sweep of pairwise checks against the values past it. Watch how fast that work piles up as the array grows.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = list(nums)\nfor i in range(len(result)):\n    for j in range(i + 1, len(result)):\n        if result[j] < result[i]:\n            result[i], result[j] = result[j], result[i]\nreturn result","steps":[{"id":"compare-first","title":"Compare result[0] against the rest","codeLine":4,"summary":"result starts as a copy of nums, [3, -1, 1, 3]. To settle position 0, compare 3 against -1, 1, 3 and swap the smaller forward.","state":{"nums":[3,-1,1,3],"i":0,"j":1,"labels":{"nums":"result"}}},{"id":"compare-restart","title":"Position 1 restarts the comparisons","codeLine":3,"summary":"After 3 settles, position 1 compares its value against everything after it, fresh comparisons that learn the order again.","state":{"nums":[-1,3,1,3],"i":1,"j":2,"labels":{"nums":"result"}}},{"id":"compare-more","title":"Each position runs its own sweep of comparisons","codeLine":4,"summary":"Position 2 compares against position 3. Every position pays its own run of comparisons against the values past it.","state":{"nums":[-1,1,3,3],"i":2,"j":3,"labels":{"nums":"result"}}},{"id":"done","title":"Sorted, after about n^2 comparisons","codeLine":6,"summary":"result becomes [-1, 1, 3, 3] and nums is untouched. Four values cost roughly six comparisons; a thousand values would cost about half a million.","state":{"nums":[-1,1,3,3],"i":3,"labels":{"nums":"result"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = Array.from(nums);\nfor (let i = 0; i < result.length; i++) {\n    for (let j = (i + 1); j < result.length; j++) {\n        if (result[j] < result[i]) {\n            const entry = [result[j], result[i]];\n            result[i] = entry[0];\n            result[j] = entry[1];\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":11},"statementBundles":{"5":{"startLine":5,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result = Array.from(nums);\nfor (let i = 0; i < result.length; i++) {\n    for (let j = (i + 1); j < result.length; j++) {\n        if (result[j] < result[i]) {\n            const entry = [result[j], result[i]];\n            result[i] = entry[0];\n            result[j] = entry[1];\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":11},"statementBundles":{"5":{"startLine":5,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> result = new ArrayList<Integer>(nums);\nfor (int i = 0; i < result.size(); i++) {\n    for (int j = (i + 1); j < result.size(); j++) {\n        if (result.get(j) < result.get(i)) {\n            List<Integer> entry = new ArrayList<>(List.of(result.get(j), result.get(i)));\n            result.set(i, entry.get(0));\n            result.set(j, entry.get(1));\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":11},"statementBundles":{"5":{"startLine":5,"endLine":10}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> result = new(nums);\nfor (int i = 0; i < result.Count; i++) {\n    for (int j = i + 1; j < result.Count; j++) {\n        if (result[j] < result[i]) {\n            List<int> entry = new() { result[j], result[i] };\n            result[i] = entry[0];\n            result[j] = entry[1];\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":11},"statementBundles":{"5":{"startLine":5,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> result = nums;\nfor (int i = 0; i < result.size(); i++) {\n    for (int j = (i + 1); j < result.size(); j++) {\n        if (result[j] < result[i]) {\n            pair<int, int> entry{result[j], result[i]};\n            result[i] = entry.first;\n            result[j] = entry.second;\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":11},"statementBundles":{"5":{"startLine":5,"endLine":10}}}}},"body":["Copy nums into result, then for each position scan everything after it and swap a smaller value forward, leaving the original untouched."]},{"id":"waste-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the cost","title":"How do the nested comparisons scale as the array grows?","workspacePanel":"trace","summary":"Four values cost about 6 comparisons; now scale the same nested sweeps to 1000 values.","options":[{"id":"grows-quadratic","label":"About half a million comparisons, roughly the square of the count","rationale":"Every position compares against the rest, so the work grows with the count times itself, about n^2. At 1000 values that is around 500,000 comparisons.","isCorrect":true},{"id":"grows-linear","label":"About a thousand comparisons, one per value","rationale":"A single pass would be linear, but each position runs its own full inner sweep, so the passes stack into n^2.","isCorrect":false},{"id":"grows-log","label":"About ten comparisons, since sorting halves the work each time","rationale":"Halving is what merge sort buys with extra structure. Plain pairwise comparison never halves anything, so the work stays quadratic.","isCorrect":false}],"answer":"Around half a million, roughly n^2. Each of the 1000 positions sweeps the others, so the comparison count climbs with the square of the array length while the value range stayed tiny the whole time."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"Which question retires the comparisons?","workspacePanel":"visualizer","quiz":{"contract":"pattern-recognition-v1","question":"Which question, answered in one step, would replace comparing pairs?","signalPrompt":"The values run from -10^4 to 10^4, a bounded line. Pick the question that line lets you answer directly.","options":[{"id":"sorting-linear","label":"How many times does each value appear?","signal":"Every value fits on a bounded number line, so its occurrences can be tallied in one pass.","rationale":"One pass can record every value's multiplicity without comparing it to another input value. The counts preserve all duplicates; the next step is to determine how those counts recover numeric order.","isCorrect":true},{"id":"sorting-divide-conquer","label":"Which half holds the smaller values?","signal":"Splitting and merging halves sorts by comparison, the work the bounded range lets us skip.","rationale":"Merge sort spends n log n comparisons even when the value range is small, so it ignores the cue.","isCorrect":false},{"id":"heap","label":"What is the next smallest item to pull?","signal":"Repeatedly extracting the minimum orders the values, but it reorders work the counts already settle.","rationale":"A heap pays log n per item to surface the next minimum, extra ordering on top of values that can be counted.","isCorrect":false},{"id":"binary-search","label":"Where does a target boundary fall?","signal":"Binary search narrows toward one boundary in a monotonic range.","rationale":"The task emits every value in order; there is no single boundary to find.","isCorrect":false}],"missFeedback":"The bounded value line gives every possible value a finite place to be counted, so one input scan can preserve every occurrence without pair comparisons.","hint":"The clue is where each value sits on the bounded number line."},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-count-slots","state":{"nums":[3,-1,1,3],"seen":{},"labels":{"nums":"nums","seen":"counts"}}}]}},{"id":"sweep-discovery","chapter":"The idea","kind":"case-probe","eyebrow":"Choose the move","title":"Given each value’s count, how do you rebuild sorted order?","workspacePanel":"visualizer","summary":"These are the tallies for nums = [3, -1, 1, 3]: one -1, one 1, two 3s.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"counts-only","state":{"seen":{"1":1,"3":2,"-1":1},"labels":{"seen":"counts"}}}]},"options":[{"id":"sweep-low-high","label":"Walk the value range from the lowest value up, emitting each value its count of times","rationale":"Climbing the number line visits values in order, so emitting each present value by its count writes -1, then 1, then 3, 3 already sorted.","isCorrect":true},{"id":"emit-keys","label":"Emit the counted values in the order they were tallied","rationale":"The tally was filled by input order. Reading -1, 1, 3 in tally order only works here by accident; sorted output must follow numeric order.","isCorrect":false},{"id":"compare-keys","label":"Compare the counted values against each other to order them","rationale":"That brings back the comparisons the counts were meant to retire. The number line already orders the values for free.","isCorrect":false}],"answer":"Sweep the value range low to high and emit each value its count of times. The sweep itself supplies the order, so [3, -1, 1, 3] rebuilds as [-1, 1, 3, 3]."},{"id":"approach-selection","chapter":"The idea","kind":"info","eyebrow":"Name what you built","title":"The count-and-sweep method is Counting Sort","workspacePanel":"visualizer","body":["You have now chosen both pieces: tally how many times each bounded value appears, then walk the numeric range from low to high and emit each value by its count.","That is Counting Sort. Its work depends on the input length plus the width of the value range, so it is a strong fit here because the problem promises a small bounded line."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"nums":[3,-1,1,3],"labels":{"nums":"nums","seen":"counts"},"seen":{}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Tally the values, then sweep the line","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"nums":[3,-1,1,3],"labels":{"nums":"nums","seen":"counts"}}}]},"body":["One pass over nums = [3, -1, 1, 3] tallies how often each value occurs: one -1, one 1, two 3s.","The sweep then climbs the value range from the minimum, -1, to the maximum, 3, stopping at every value in between. At each stop, decide what gets written before you watch the trace."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the sweep","title":"Count, sweep, then read off [3, -1, 1, 3]","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-count","state":{"nums":[3,-1,1,3],"labels":{"nums":"nums","seen":"counts"},"seen":{"1":1,"3":2,"-1":1},"min_val":-1,"max_val":3}},{"id":"sweep-gap","state":{"nums":[3,-1,1,3],"seen":{"1":1,"3":2,"-1":1},"seenHighlight":0,"labels":{"nums":"nums","seen":"counts"}}},{"id":"emit-result","state":{"arrays":[{"name":"result","values":[-1,1]}],"seen":{"1":1,"3":2,"-1":1},"seenHighlight":3,"labels":{"seen":"counts"}}}]},"beats":[{"id":"after-count","title":"Which value does the sweep emit first?","summary":"The count table holds entries for -1, 1, and 3, spanning the range shown.","prompt":"The tally is done and result is still empty.","options":[{"id":"emit-min","label":"The numeric minimum across the counted values","rationale":"The sweep climbs the value range from its low end, so the smallest counted value lands before any larger one.","isCorrect":true},{"id":"emit-first-tallied","label":"The value tallied first, since the table fills in input order","rationale":"Tally order followed the input. The sweep ignores it and walks the number line. The first emitted value is the smallest counted value.","isCorrect":false},{"id":"emit-most","label":"The most frequent value, since its count is largest","rationale":"Count size sets how many times a value is emitted, not when. Order comes from the value on the line, not from how often it appears.","isCorrect":false}],"answer":"The numeric minimum, -1, is emitted first. The sweep begins at the lowest counted value and climbs, so the smallest value leads."},{"id":"sweep-gap","title":"The sweep climbs to value 0. What does it emit?","summary":"The sweep has passed -1 and now sits at value 0 on the line.","prompt":"The sweep is at value 0, between -1 and 1.","options":[{"id":"emit-nothing","label":"Nothing, and the sweep moves on to value 1","rationale":"A value with no count contributes no copies, so 0 is skipped while the sweep keeps climbing in order.","isCorrect":true},{"id":"emit-zero-once","label":"A single 0, to fill the gap","rationale":"0 was never in the input, so emitting it would invent a value the array never held.","isCorrect":false},{"id":"stop-sweep","label":"It stops, since the gap ends the range","rationale":"A missing value is not the end of the range. The sweep continues to the maximum, 3, past every gap.","isCorrect":false}],"answer":"Value 0 emits nothing and the sweep continues. Absent values cost only a step, and walking past them keeps the order intact."},{"id":"emit-result","title":"The sweep reaches its last value, 3. What does result become?","summary":"result holds [-1, 1], and the sweep has arrived at value 3.","prompt":"The sweep is at 3, the final value in the range.","options":[{"id":"append-two","label":"[-1, 1, 3, 3], both 3s appended","rationale":"Value 3 was counted twice, so the sweep emits it twice, completing the sorted copy [-1, 1, 3, 3].","isCorrect":true},{"id":"append-one","label":"[-1, 1, 3], one 3 appended","rationale":"Emitting 3 only once drops a copy. The count of 2 is exactly the instruction to append it twice.","isCorrect":false},{"id":"append-count","label":"[-1, 1, 2], appending the count instead of the value","rationale":"The value emitted is 3. The count says how many 3s to write.","isCorrect":false}],"answer":"result becomes [-1, 1, 3, 3]. The count of 2 emits two 3s, and the low-to-high sweep leaves them in sorted order."}]},{"id":"emit-order-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can range(min_val, max_val) cover the whole sweep?","workspacePanel":"trace","summary":"The sweep has to run from the minimum up to the largest value present. A natural way to write that bound is range(min_val, max_val), which reads as min through max. It emits duplicates correctly and the lower values come out in order, so the shape looks right. Watch it finish on [3, -1, 1, 3], where the largest value is 3.","pitfall":"The code below sweeps with range(min_val, max_val), the bound that reads as covering min through max. Follow where the loop actually stops.","whyItMatters":"range(min_val, max_val) stops one short of max_val, so the largest value is never swept and every copy of it is lost. The bound must be inclusive: sweep range(min_val, max_val + 1) so the maximum value gets its turn and its counted copies reach the output.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"counts = {}\nmin_val = nums[0]\nmax_val = nums[0]\nfor num in nums:\n    counts[num] = counts.get(num, 0) + 1\n    if num < min_val:\n        min_val = num\n    if num > max_val:\n        max_val = num\nresult = []\nfor value in range(min_val, max_val):\n    if value in counts:\n        for _ in range(counts[value]):\n            result.append(value)\nreturn result","steps":[{"id":"counts-ready","title":"nums = [3, -1, 1, 3]: the largest value is 3","codeLine":5,"summary":"The tally gives one -1, one 1, two 3s, and the bounds settle at min -1 and max 3. The correct output is [-1, 1, 3, 3].","state":{"seen":{"1":1,"3":2,"-1":1},"labels":{"seen":"counts"}}},{"id":"emit-low","title":"-1 then 1 reach result","codeLine":14,"summary":"The sweep starts at -1 and emits it, skips 0, reaches 1 and emits it. result is [-1, 1], correct so far.","state":{"arrays":[{"name":"result","values":[-1,1]}],"seen":{"1":1,"3":2,"-1":1},"seenHighlight":1,"labels":{"seen":"counts"}}},{"id":"stop-before-max","title":"The loop ends at 2, one short of 3","codeLine":12,"summary":"range(min_val, max_val) is range(-1, 3), whose last value is 2. The loop tests 2, finds no count, and ends. Value 3 is never visited, so its count of 2 sits unread.","state":{"arrays":[{"name":"result","values":[-1,1]}],"seen":{"1":1,"3":2,"-1":1},"seenHighlight":3,"labels":{"seen":"counts"}}},{"id":"short","title":"Both 3s missing from the output","codeLine":15,"summary":"It returns [-1, 1]. The values written are in order, but the maximum, 3, was never swept, so both of its copies are gone and two values come out where four went in.","state":{"arrays":[{"name":"result","values":[-1,1]}],"seen":{"1":1,"3":2,"-1":1},"labels":{"seen":"counts"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const counts = new Map();\nlet minVal = nums[0];\nlet maxVal = nums[0];\nfor (const num of nums) {\n    counts.set(num, (counts.has(num) ? counts.get(num) : 0) + 1);\n    if (num < minVal) {\n        minVal = num;\n    }\n    if (num > maxVal) {\n        maxVal = num;\n    }\n}\nconst result = [];\nfor (let value = minVal; value < maxVal; value++) {\n    if (counts.has(value)) {\n        for (let i = 0; i < counts.get(value); i++) {\n            result.push(value);\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13,"11":14,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12},"14":{"startLine":17,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const counts: Map<number, number> = new Map();\nlet minVal = nums[0];\nlet maxVal = nums[0];\nfor (const num of nums) {\n    counts.set(num, (counts.has(num) ? counts.get(num)! : 0) + 1);\n    if (num < minVal) {\n        minVal = num;\n    }\n    if (num > maxVal) {\n        maxVal = num;\n    }\n}\nconst result: Array<number> = [];\nfor (let value = minVal; value < maxVal; value++) {\n    if (counts.has(value)) {\n        for (let i = 0; i < counts.get(value)!; i++) {\n            result.push(value);\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13,"11":14,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12},"14":{"startLine":17,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"Map<Integer, Integer> counts = new HashMap<Integer, Integer>();\nint minVal = nums.get(0);\nint maxVal = nums.get(0);\nfor (Integer num : nums) {\n    counts.put(num, (counts.getOrDefault(num, 0) + 1));\n    if (num < minVal) {\n        minVal = num;\n    }\n    if (num > maxVal) {\n        maxVal = num;\n    }\n}\nList<Integer> result = new ArrayList<>();\nfor (int value = minVal; value < maxVal; value++) {\n    if (counts.containsKey(value)) {\n        for (int i = 0; i < counts.get(value); i++) {\n            result.add(value);\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13,"11":14,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12},"14":{"startLine":17,"endLine":20}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"Dictionary<int, int> counts = new();\nint minVal = nums[0];\nint maxVal = nums[0];\nforeach (int num in nums) {\n    counts[num] = (counts.ContainsKey(num) ? counts[num] : 0) + 1;\n    if (num < minVal) {\n        minVal = num;\n    }\n    if (num > maxVal) {\n        maxVal = num;\n    }\n}\nList<int> result = new();\nfor (int value = minVal; value < maxVal; value++) {\n    if (counts.ContainsKey(value)) {\n        for (int i = 0; i < counts[value]; i++) {\n            result.Add(value);\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13,"11":14,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12},"14":{"startLine":17,"endLine":20}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"unordered_map<int, int> counts;\nint min_val = nums[0];\nint max_val = nums[0];\nfor (int num : nums) {\n    counts[num] += 1;\n    if (num < min_val) {\n        min_val = num;\n    }\n    if (num > max_val) {\n        max_val = num;\n    }\n}\nvector<int> result;\nfor (int value = min_val; value < max_val; value++) {\n    if (counts.count(value)) {\n        for (int i = 0; i < counts.at(value); i++) {\n            result.push_back(value);\n        }\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13,"11":14,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12},"14":{"startLine":17,"endLine":20}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","summary":"The sweep handled the mixed array. Two failure modes are worth a check before coding: empty input and negative values.","ctaLabel":"Check edge cases","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[3,-1,1,3],"labels":{"nums":"nums"}}}]},"body":["Two inputs deserve a check: an empty array, and an array whose values run below zero.","Trace each one and decide what, if anything, the rule needs added to handle it."]},{"id":"empty-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"For nums = [], what must happen before the range is read?","workspacePanel":"visualizer","summary":"There is no first value to seed the minimum and maximum from.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-state","state":{"arrays":[{"name":"nums","values":[]}]}}]},"options":[{"id":"return-empty","label":"Return an empty array before reading any value","rationale":"Seeding the range from nums[0] needs a first value. With none, returning the empty copy up front avoids reading a value that is not there.","isCorrect":true},{"id":"sweep-zero","label":"Sweep from 0 to 0 and emit nothing","rationale":"There is no value to fix the range, so picking 0 is arbitrary. The clean answer is to return empty before touching the range at all.","isCorrect":false},{"id":"no-handling","label":"Nothing special, the loops just do not run","rationale":"Seeding min and max from nums[0] runs before the loops and is exactly what fails on an empty array, so it needs handling first.","isCorrect":false}],"answer":"Return the empty copy first. With no first value, there is nothing to seed the range from, so the guard comes before any range read."},{"id":"negative-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"For nums = [-2, 5, 0, -2, 3], where must the sweep start?","workspacePanel":"visualizer","summary":"The counts include values below zero.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"negative-state","state":{"nums":[-2,5,0,-2,3],"labels":{"nums":"nums","seen":"counts"},"seen":{"0":1,"3":1,"5":1,"-2":2}}}]},"options":[{"id":"start-min","label":"At -2, the actual minimum value","rationale":"The sweep must cover every value present, so it starts at the true minimum. Beginning at -2 lets both copies of -2 reach the output.","isCorrect":true},{"id":"start-zero","label":"At 0, since counts are usually non-negative","rationale":"Starting at 0 skips every negative value, so both -2s would never be emitted and the output would be missing them.","isCorrect":false},{"id":"shift-values","label":"At 0, after adding an offset so nothing is negative","rationale":"Shifting values would change them, but the output must hold the originals. Starting the sweep at the real minimum needs no offset.","isCorrect":false}],"answer":"Start at -2, the actual minimum. Sweeping from the true minimum carries negative values into the sorted copy."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"Tally by value, track the smallest and largest, then sweep that range emitting each value by its count.","ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[3,-1,1,3],"labels":{"nums":"nums","seen":"counts"}}}]},"body":["Walk nums once to tally how many times each value occurs, tracking the smallest and largest values you see.","Then sweep from the minimum to the maximum, emitting each present value as many times as it was counted, and return the values you collected."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the count-and-sweep sort","summary":"Now turn count-and-sweep into code: return early on an empty array and start the count table, tally each value as you pass it while tracking the smallest and largest, then sweep that range low to high emitting each value by its count, and return what you collected.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","body":["Counting sort never compares two values. It tallies how often each appears, then walks the bounded value line in order, and the walk itself supplies the sorted order.","It costs one pass over nums plus one pass over the value range, so the work is O(n + R), down from the pairwise comparison sort’s O(n^2), whenever R, the value range, is small."],"takeaways":[{"title":"Counts replace comparisons","body":"Tallying each value lets a bounded range be sorted without ever comparing two values against each other."},{"title":"The sweep supplies the order","body":"Walking values from the minimum to the maximum emits them in sorted order."},{"title":"Start from the real minimum","body":"Seeding the range from the actual min and max carries negative values through correctly."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
