{"id":"height-checker","title":"Height Checker","difficulty":"easy","patterns":["sorting-linear"],"primaryConcept":"sorting-linear","concepts":["sorting-linear"],"problemForm":"intro","companies":["Amazon","Google","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"heights","sizeMetric":"length","sizes":[8,16,32,64],"valueRange":{"min":1,"max":100}},"description":"A class of students is standing in a line. You are given `heights`, where `heights[i]` is the height of the student currently at position `i`.\n\nReturn the number of positions where the current order differs from the nondecreasing height order.","examples":[{"input":"heights = [1,1,4,2,1,3]","output":"3","explanation":"The expected order is [1,1,1,2,3,4], which differs at indices 2, 4, and 5."},{"input":"heights = [5,1,2,3,4]","output":"5","explanation":"Every position differs from the sorted order [1,2,3,4,5]."}],"constraints":[{"id":"1-len-heights-100","text":"1 <= len(heights) <= 100","check":{"kind":"sizeRange","target":"heights","measure":"arrayLength","min":1,"max":100}},{"id":"1-heights-i-100","text":"1 <= heights[i] <= 100","check":{"kind":"valueRange","target":"heights","selector":"arrayItems","min":1,"max":100}}],"starterCode":"class Solution:\n    def heightChecker(self, heights: list[int]) -> int:\n        # Your code here\n        pass","functionName":"heightChecker","testCases":[{"id":"1","input":{"heights":[1,1,4,2,1,3]},"expected":3,"description":"Canonical example."},{"id":"2","input":{"heights":[5,1,2,3,4]},"expected":5,"description":"Every position changes."},{"id":"3","input":{"heights":[1,2,3,4,5]},"expected":0,"description":"Already sorted."},{"id":"4","input":{"heights":[2,1,2,1,1,2]},"expected":4,"description":"Repeated heights."},{"id":"h1","input":{"heights":[1]},"expected":0,"description":"A single student is already in the correct order."},{"id":"h2","input":{"heights":[2,2,2]},"expected":0,"description":"Identical heights never move."},{"id":"h3","input":{"heights":[3,3,2,2,1,1]},"expected":4,"description":"Only the positions that differ from the sorted multiset count."},{"id":"h4","input":{"heights":[1,3,2,2,4,4]},"expected":2,"description":"Only the out-of-place middle values differ from sorted order."},{"id":"h5","input":{"heights":[5,1,5,1,5]},"expected":2,"description":"Alternating heights still compare against the sorted multiset."},{"id":"h6","input":{"heights":[2,3,3,2,4,4]},"expected":2,"description":"Two positions differ from the nondecreasing arrangement."}],"hints":[{"level":1,"content":"You need to know what the sorted height order would look like."},{"level":2,"content":"Heights are bounded from 1 to 100, so count frequencies instead of comparison sorting."},{"level":3,"content":"Emit the expected sorted order from the counts, then compare each original position with expected[i]."}],"guidedFlow":{"version":2,"progressRevision":"height-checker-2026-07-19-bounded-range-before-counting","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose cost matches the bounded height range.","approaches":[{"id":"comparison-sort","name":"Sort a copy","summary":"Copy the heights, sort the copy with a comparison sort, then compare positions.","decisionReason":"It is correct, but it pays O(n log n) comparison cost the bounded 1 to 100 range makes avoidable.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Sorts by comparison, ignoring that the values are small bounded integers."],"isOptimal":false},{"id":"counting-buckets","name":"Count then replay","summary":"Tally how many students have each height, then emit each height in order from its tally.","decisionReason":"One tally pass and one replay pass over the bounded range build the sorted line in O(n + k).","complexity":{"time":"O(n + k)","space":"O(n + k)"},"tradeoffs":["Holds one count per possible height, but never compares two heights."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-counts","title":"Create the count map","description":"Set up keyed state that will hold how many students stand at each height.","commonMistakes":["Sorting the heights first instead of tallying them","Using one running total for all heights instead of one count per height"],"hint":"The state holds a count per height, keyed by the height value.","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":"Initialize keyed count state before scanning the heights.","doneWhen":"A map-like count state exists before the tally scan begins.","shouldFailWhen":"The code has no keyed count state or builds it only after counting has started.","roles":["height count map"],"mustProve":["The keyed count state is initialized before the input scan."],"mustNotAccept":["A single scalar count for all heights.","Sorting the input instead of initializing count state."],"equivalentVariants":["Use a dict, map, or bounded bucket array keyed by height."],"proofSnippets":[{"id":"py-height-checker-init-counts","language":"python","code":"class Solution:\n    def heightChecker(self, heights: list[int]) -> int:\n        counts = {}"}]}},{"id":"count-heights","title":"Tally every height","description":"Scan the line and raise the stored count for each height by one.","commonMistakes":["Setting each height count to 1 and dropping repeats","Tallying the index instead of the height value"],"hint":"A repeated height should raise its own bucket each time it appears.","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":"Build height frequencies by scanning every input height.","doneWhen":"Each scanned height raises its own count bucket by one.","shouldFailWhen":"Repeated heights are not accumulated, or the scan misses elements.","roles":["current height","height count map"],"mustProve":["The input line is scanned.","The keyed count for the current height is incremented."],"mustNotAccept":["Setting every count to 1.","Counting indices instead of heights."],"equivalentVariants":["Use counts[h] = counts.get(h, 0) + 1.","Use a fixed-size bucket array and raise buckets."],"proofSnippets":[{"id":"py-height-checker-count-heights","language":"python","code":"class Solution:\n    def heightChecker(self, heights: list[int]) -> int:\n        counts = {}\n        for height in heights:\n            counts[height] = counts.get(height, 0) + 1"}]}},{"id":"init-expected","title":"Start the expected line","description":"Create a separate output sequence that will hold the sorted order, leaving the original line untouched.","commonMistakes":["Sorting the heights back into the input array","Forgetting to make a place to build the expected order"],"hint":"Keep the original line intact so the final compare has two sequences to read.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Initialize the expected sorted sequence before emitting from counts.","doneWhen":"An empty result sequence exists for the sorted expectation.","shouldFailWhen":"The code has no separate output sequence or overwrites the input as its only storage.","roles":["expected order sequence"],"mustProve":["A result sequence is initialized."],"mustNotAccept":["Using the original heights line as the only output state."],"equivalentVariants":["Use an empty list or array."],"proofSnippets":[{"id":"py-height-checker-init-expected","language":"python","code":"class Solution:\n    def heightChecker(self, heights: list[int]) -> int:\n        counts = {}\n        for height in heights:\n            counts[height] = counts.get(height, 0) + 1\n        expected = []"}]}},{"id":"emit-expected","title":"Replay the sorted order","description":"Walk the height range from low to high and append each height as many times as it was tallied.","commonMistakes":["Appending each height once and dropping its duplicates","Walking the height range from high to low"],"hint":"For each height, append it as many times as its count.","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":"Build the nondecreasing expected order from the frequency counts.","doneWhen":"The code appends each height to the result once for every counted occurrence, in increasing order.","shouldFailWhen":"Duplicates are lost or the range is emitted in descending or random order.","roles":["height range","height count","expected order sequence"],"mustProve":["The code scans candidate height values.","The result sequence receives values from that scan."],"mustNotAccept":["Appending one copy regardless of count.","Using a comparison sort instead of count replay."],"equivalentVariants":["Use nested loops over height and its count.","Use a while loop that appends and lowers the bucket count."],"proofSnippets":[{"id":"py-height-checker-emit-expected","language":"python","code":"class Solution:\n    def heightChecker(self, heights: list[int]) -> int:\n        counts = {}\n        for height in heights:\n            counts[height] = counts.get(height, 0) + 1\n        expected = []\n        for height in range(1, 101):\n            if height in counts:\n                for _ in range(counts[height]):\n                    expected.append(height)"}]}},{"id":"count-mismatches","title":"Count positions that differ","description":"Walk the two lines by index and raise the mismatch count only when the values at that position differ.","commonMistakes":["Comparing values from different positions","Raising the count for matching positions"],"hint":"At index i, compare heights[i] with expected[i]; only inequality should add one.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"counts_paired_index_mismatches","scope":"compare-positions","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Count positions whose original and expected values differ.","doneWhen":"Two distinct sequences are compared at the same scan index and the mismatch branch increments a counter by one.","shouldFailWhen":"The code compares only one sequence, uses different indices, increments unconditionally, or increments on equality.","roles":["original sequence","expected sequence","shared index","mismatch counter"],"mustProve":["Two distinct sequences are read at the same index.","The branch representing inequality increments a scalar counter by one."],"mustNotAccept":["An unconditional counter increment.","A comparison against a constant or against the same sequence.","Incrementing the counter when the paired values are equal."],"equivalentVariants":["Increment inside an inequality branch.","Increment in the else branch of an equality check."],"proofSnippets":[{"id":"py-height-checker-count-mismatches","language":"python","code":"class Solution:\n    def heightChecker(self, heights: list[int]) -> int:\n        expected = []\n        mismatches = 0\n        for i in range(len(heights)):\n            if heights[i] != expected[i]:\n                mismatches += 1"},{"id":"js-height-checker-count-mismatches","language":"javascript","code":"class Solution {\n  heightChecker(heights) {\n    const expected = [];\n    let mismatches = 0;\n    for (let i = 0; i < heights.length; i++) {\n      if (heights[i] !== expected[i]) mismatches += 1;\n    }\n  }\n}"}]}},{"id":"return-mismatches","title":"Return the mismatch count","description":"Compare each original position with the expected position and return how many differ.","commonMistakes":["Returning the expected line instead of the count","Counting positions that match instead of positions that differ"],"hint":"Raise the answer only when the original height differs from the expected height at that index.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the final accumulator counting positions that differ from the expected order.","doneWhen":"The function returns the mismatch counter after comparing every position.","shouldFailWhen":"The function returns the sorted line, a boolean, or a partial count.","roles":["mismatch counter","original heights","expected order"],"mustProve":["A numeric result is returned after the comparison pass."],"mustNotAccept":["Returning the expected line instead of the count.","Returning before every position is compared."],"equivalentVariants":["Return the mismatch accumulator directly.","Sum over differing positions if it yields the same count."],"proofSnippets":[{"id":"py-height-checker-return-mismatches","language":"python","code":"class Solution:\n    def heightChecker(self, heights: list[int]) -> int:\n        counts = {}\n        for height in heights:\n            counts[height] = counts.get(height, 0) + 1\n        expected = []\n        for height in range(1, 101):\n            if height in counts:\n                for _ in range(counts[height]):\n                    expected.append(height)\n        mismatches = 0\n        for i in range(len(heights)):\n            if heights[i] != expected[i]:\n                mismatches += 1\n        return mismatches"}]}}],"slides":[{"id":"opener","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Count who stands out of order","workspacePanel":"problem","body":["You get heights, the height of each student standing in a line. Compare the line to the order it should be in: nondecreasing, shortest to tallest. Return how many positions hold a different height in the two orders.","The constraints give us one more fact to work with: every height is an integer from 1 through 100.","The plain way is to sort a copy of the line and compare. Watch it work, and watch what it costs."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The plain way","title":"Sort a copy, then compare","summary":"Sorting a copy and comparing positions gets the count right, but the sort weighs heights against each other to discover their order. Which part of that work could the known 1-through-100 range replace?","workspacePanel":"trace","body":["Sort a copy of the line into the expected order, then count the positions that differ."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"expected = sorted(heights)\nmismatches = 0\nfor i in range(len(heights)):\n    if heights[i] != expected[i]:\n        mismatches += 1\nreturn mismatches","steps":[{"id":"sort-copy","title":"A comparison sort orders the copy","codeLine":1,"summary":"heights = [1, 1, 4, 2, 1, 3]. The sort compares heights against each other to land on the expected copy [1, 1, 1, 2, 3, 4].","state":{"rows":[{"label":"heights","values":[1,1,4,2,1,3]},{"label":"expected","values":[1,1,1,2,3,4],"changed":[0,1,2,3,4,5]}]}},{"id":"compare-match","title":"Position 1 already matches","codeLine":4,"summary":"heights[1] is 1 and expected[1] is 1, so this position does not count.","state":{"nums":[1,1,4,2,1,3],"i":1,"labels":{"nums":"heights"}}},{"id":"compare-diff","title":"Position 2 differs","codeLine":5,"summary":"heights[2] is 4 but expected[2] is 1, so the mismatch count rises.","state":{"nums":[1,1,4,2,1,3],"i":2,"labels":{"nums":"heights"}}},{"id":"compare-end","title":"The scan finishes at three","codeLine":3,"summary":"Positions 4 and 5 differ too. Three mismatches, but the sort compared heights pair against pair to get here.","state":{"nums":[1,1,4,2,1,3],"i":5,"labels":{"nums":"heights"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const expected = [...heights].sort((a, b) => a - b);\nlet mismatches = 0;\nfor (let i = 0; i < heights.length; i++) {\n    if (heights[i] !== expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const expected = [...heights].sort((a, b) => a - b);\nlet mismatches = 0;\nfor (let i = 0; i < heights.length; i++) {\n    if (heights[i] !== expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> expected = new ArrayList<>(heights);\nCollections.sort(expected);\nint mismatches = 0;\nfor (int i = 0; i < heights.size(); i++) {\n    if (heights.get(i) != expected.get(i)) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":3,"3":4,"4":5,"5":6,"6":9},"statementBundles":{"1":{"startLine":1,"endLine":2},"5":{"startLine":6,"endLine":8}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> expected = heights.OrderBy(value => value).ToList();\nint mismatches = 0;\nfor (int i = 0; i < heights.Count; i++) {\n    if (heights[i] != expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> expected = sortedVector(heights);\nint mismatches = 0;\nfor (int i = 0; i < heights.size(); i++) {\n    if (heights[i] != expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}}}}},{"id":"waste-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the waste","title":"What work is sorted(heights) doing on that first line?","workspacePanel":"trace","summary":"The expected line came out right, but the sorted(heights) call on line 1 is where the time goes over [1, 1, 4, 2, 1, 3].","options":[{"id":"compares-pairs","label":"Weighing heights against each other, pair by pair, to decide their order","rationale":"sorted(heights) is a comparison sort: it repeatedly compares heights against one another to settle their global order, paying O(n log n) in pairwise comparisons.","isCorrect":true},{"id":"recounts-length","label":"Measuring the length of the line again on every comparison","rationale":"The length is read once and never changes; it is not the repeated cost inside the sort.","isCorrect":false},{"id":"rebuilds-copy","label":"Rebuilding the copy of the line for each position compared","rationale":"The copy is made once when sorted(heights) runs, not rebuilt per comparison. The repeated cost is the comparing itself.","isCorrect":false}],"answer":"sorted(heights) spends its time repeatedly comparing heights pair against pair to settle their global order, which is the O(n log n) cost. That pairwise comparison work is the waste to look for a way around."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the signal","title":"Which fact lets the order be built without comparing heights?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bounded-range-state","state":{"nums":[1,1,4,2,1,3],"seen":{"1":0,"2":0,"3":0,"4":0},"labels":{"nums":"heights","seen":"buckets"}}}]},"quiz":{"contract":"pattern-recognition-v1","question":"Which fact about the heights lets the sorted line be built without comparing pairs?","signalPrompt":"For heights = [1, 1, 4, 2, 1, 3], which property turns \"what is the sorted order\" into a single tally and replay?","options":[{"id":"bounded-range","label":"Every height is an integer between 1 and 100","signal":"A fixed, small set of possible values can be tallied, then replayed in order.","rationale":"Because there are only 100 possible heights, one tally pass and one low-to-high replay build the sorted order in O(n + 100), with no pairwise comparisons.","isCorrect":true},{"id":"pick-shortest","label":"You can keep pulling out the next shortest student","signal":"That orders the line, but pays extraction cost the bounded range removes.","rationale":"Repeatedly extracting a minimum is heap or selection work; a value tally skips it.","isCorrect":false},{"id":"monotonic-boundary","label":"A single threshold splits short students from tall","signal":"That fits a yes/no boundary search, but here every position has to be placed.","rationale":"There is no monotonic predicate to search; the whole order is needed.","isCorrect":false},{"id":"few-distinct","label":"The line is already almost in order","signal":"Near-sortedness can help some sorts, but it is not promised by the input.","rationale":"The line can be in any order, so the speedup cannot rely on it; the bounded value range is what always holds.","isCorrect":false}],"missFeedback":"The decisive fact is the bounded value range: tally how many of each height, then replay them in order."}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which cost should we build for?","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"How should we use the bounded height range?","decisionPrompt":"Choose the method that replaces pairwise ordering with one bucket per possible height.","approaches":[{"id":"comparison-sort","name":"Sort a copy","summary":"Copy the heights, comparison-sort the copy, then compare aligned positions.","decisionReason":"It is correct, but it keeps paying O(n log n) to rediscover an order the fixed value range already gives us.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Works without a small value bound, but ignores the useful 1-through-100 constraint."],"isOptimal":false},{"id":"counting-buckets","name":"Count each height, then replay","summary":"Store how many students have each possible height, then emit heights from 1 through 100.","decisionReason":"The numeric bucket order is already the required sorted order, so tallying and replaying take O(n + 100).","complexity":{"time":"O(n + 100)","space":"O(n + 100)"},"tradeoffs":["Uses one bucket per possible height and avoids comparing heights with each other."],"isOptimal":true}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"nums":[1,1,4,2,1,3],"seen":{"1":3,"2":1,"3":1,"4":1},"labels":{"nums":"heights","seen":"counts"}}}]}},{"id":"state-meaning","chapter":"The idea","kind":"case-probe","eyebrow":"Set up the state","title":"What does the count map hold after tallying the line?","summary":"One tally pass over [1, 1, 4, 2, 1, 3] fills it before any expected position is built.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-meaning-state","state":{"nums":[1,1,4,2,1,3],"i":5,"seen":{"1":3,"2":1,"3":1,"4":1},"labels":{"nums":"heights","seen":"counts"}}}]},"options":[{"id":"counts-per-height","label":"Each height mapped to how many students stand at it: 1 to 3, 2 to 1, 3 to 1, 4 to 1","rationale":"The tally records multiplicity, so the replay can emit height 1 three times and the others once each.","isCorrect":true},{"id":"heights-as-set","label":"Just the set of heights that appear: 1, 2, 3, 4","rationale":"A set drops the counts, so it could not know that three students stand at height 1.","isCorrect":false},{"id":"positions-map","label":"Each height mapped to the position where it first appears","rationale":"The replay needs how many of each height there are, not where one first showed up.","isCorrect":false}],"answer":"The map is the line as counts: 1 to 3, 2 to 1, 3 to 1, 4 to 1. It records how many students stand at each height."},{"id":"replay-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"How many times must each height enter the expected line?","summary":"The counts are just a tally until one rule turns them back into a line.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"replay-invariant-state","state":{"nums":[1,1,4,2,1,3],"seen":{"1":3,"2":1,"3":1,"4":1},"seenHighlight":1,"labels":{"nums":"heights","seen":"counts"}}}]},"options":[{"id":"count-times","label":"As many times as its count: height 1 enters three times, each of 2, 3, 4 once","rationale":"Emitting each height count times keeps the expected line the same length as the input and in nondecreasing order.","isCorrect":true},{"id":"once-each","label":"Once for each height that has any count","rationale":"Emitting each height once would give [1, 2, 3, 4], four positions for a six-student line, losing the duplicate 1s.","isCorrect":false},{"id":"descending","label":"From the tallest height down to the shortest","rationale":"Walking high to low builds the reverse order; the expected line is nondecreasing.","isCorrect":false}],"answer":"Each height enters the line as many times as its count, walking low to high: three 1s, then one 2, one 3, one 4."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"A full tally, an empty line so far","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[1,1,4,2,1,3],"seen":{"1":3,"2":1,"3":1,"4":1},"arrays":[{"name":"expected","values":["·","·","·","·","·","·"]}],"labels":{"nums":"heights","seen":"counts"}}}]},"body":["The line [1, 1, 4, 2, 1, 3] is already tallied to 1: 3, 2: 1, 3: 1, 4: 1, and the expected line is still empty. Now those counts replay into the expected order, and the two lines get compared position by position.","Each stage does one thing: tally, then replay low to high, then count the positions that differ."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the build","title":"Trace tally, then compare","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"tally-ones","state":{"nums":[1,1,4,2,1,3],"seen":{"1":3,"2":1,"3":1,"4":1},"seenHighlight":1,"labels":{"nums":"heights","seen":"counts"}}},{"id":"compare-position-2","state":{"rows":[{"label":"heights","values":[1,1,4,2,1,3]},{"label":"expected","values":[1,1,1,2,3,4]}],"i":2}}]},"beats":[{"id":"tally-ones","title":"What does the count for height 1 hold?","summary":"The line [1, 1, 4, 2, 1, 3] has just been tallied into the counts.","prompt":"The bucket for height 1 has just finished filling.","options":[{"id":"three","label":"3, because three students stand at height 1","rationale":"Each height 1 in the line raised the bucket once, so it lands at 3.","isCorrect":true},{"id":"one","label":"1, because height 1 appears in the line","rationale":"A set would only say height 1 appears. The tally records three students at height 1.","isCorrect":false},{"id":"two","label":"2, the number of other heights besides 1","rationale":"The bucket counts students at height 1, not how many other heights exist.","isCorrect":false}],"answer":"Three students stand at height 1, so its count is 3. The others, 2, 3, and 4, each hold 1."},{"id":"compare-position-2","title":"Does position 2 add to the mismatch count?","summary":"The replay is done, and the compare pass has reached index 2.","prompt":"Read the two aligned entries at index 2.","options":[{"id":"counts","label":"Yes: the original holds 4 there but the expected holds 1","rationale":"The two heights at index 2 differ, so this position is one of the mismatches.","isCorrect":true},{"id":"matches","label":"No: both lines hold the same height at index 2","rationale":"The original is 4 and the expected is 1 at index 2, so they do not match.","isCorrect":false},{"id":"every-position","label":"Yes, and so does every other position, for 6 total","rationale":"Positions 0, 1, and 3 already match; only 2, 4, and 5 differ, for 3 total.","isCorrect":false}],"answer":"Index 2 differs, 4 against 1, so it counts. With indices 4 and 5 also differing, the answer is 3."}]},{"id":"inplace-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can the replay just walk the count map as built?","summary":"Emitting each stored height its count of times gets the multiplicity right, so it can look like the replay rule. Watch it on [3, 1, 3, 2].","workspacePanel":"trace","pitfall":"The code below replays heights in the order their keys were inserted into the count map rather than in increasing height order.","whyItMatters":"Replay the heights from the lowest value upward, not in the order the map happened to learn them. Walking the keys in arrival order builds an expected line that is not sorted, so the compare measures the original against a scrambled order and the count comes out wrong.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"counts = {}\nfor height in heights:\n    counts[height] = counts.get(height, 0) + 1\nexpected = []\nfor height in counts:\n    for _ in range(counts[height]):\n        expected.append(height)\nmismatches = 0\nfor i in range(len(heights)):\n    if heights[i] != expected[i]:\n        mismatches += 1\nreturn mismatches","steps":[{"id":"tally-counts","title":"The map learns heights in arrival order","codeLine":3,"summary":"heights = [3, 1, 3, 2] tallies to 3: 2, 1: 1, 2: 1. The keys land in the order each height was first seen, tracked by key order: 3, then 1, then 2.","state":{"nums":[3,1,3,2],"seen":{"1":1,"2":1,"3":2},"arrays":[{"name":"key order","values":[3,1,2]}],"labels":{"nums":"heights","seen":"counts"}}},{"id":"emit-arrival","title":"Replaying the keys as stored emits 3, 3, 1, 2","codeLine":7,"summary":"Walking the map in key order [3, 1, 2] appends two 3s, then one 1, then one 2, so expected is [3, 3, 1, 2], the multiplicities right but the order scrambled.","state":{"nums":[3,3,1,2],"seen":{"1":1,"2":1,"3":2},"arrays":[{"name":"key order","values":[3,1,2]}],"labels":{"nums":"expected","seen":"counts"}}},{"id":"scrambled-compare","title":"The compare reads against an unsorted expected line","codeLine":10,"summary":"At index 1 the original holds 1 while expected holds 3, and at index 2 the original holds 3 while expected holds 1. Both mismatch because expected was never sorted.","state":{"rows":[{"label":"heights","values":[3,1,3,2]},{"label":"expected","values":[3,3,1,2]}],"i":1}},{"id":"wrong-count","title":"Two mismatches, but the line was never ordered","codeLine":12,"summary":"The scan returns 2, yet the true expected order [1, 2, 3, 3] differs from the original at three positions. Replaying in arrival order undercounts because expected itself is out of order.","state":{"rows":[{"label":"heights","values":[3,1,3,2]},{"label":"expected","values":[3,3,1,2]}],"i":3}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const counts = new Map();\nfor (const height of heights) {\n    counts.set(height, (counts.has(height) ? counts.get(height) : 0) + 1);\n}\nconst expected = [];\nfor (const height of counts.keys()) {\n    for (let i = 0; i < counts.get(height); i++) {\n        expected.push(height);\n    }\n}\nlet mismatches = 0;\nfor (let i = 0; i < heights.length; i++) {\n    if (heights[i] !== expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":14,"12":17},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"11":{"startLine":14,"endLine":16}},"alternateStyles":{"close-to-source":{"code":"const counts = new Map();\nfor (const height of heights) {\n    counts.set(height, (counts.has(height) ? counts.get(height) : 0) + 1);\n}\nconst expected = [];\nfor (const height of counts.keys()) {\n    const end = counts.get(height);\n    if (end === undefined) throw new Error(\"KeyError\");\n    for (let i = 0; i < end; i++) {\n        expected.push(height);\n    }\n}\nlet mismatches = 0;\nfor (let i = 0; i < heights.length; i++) {\n    if (heights[i] !== expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":10,"8":13,"9":14,"10":15,"11":16,"12":19},"statementBundles":{"3":{"startLine":3,"endLine":4},"6":{"startLine":7,"endLine":9},"7":{"startLine":10,"endLine":12},"11":{"startLine":16,"endLine":18}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const counts: Map<number, number> = new Map();\nfor (const height of heights) {\n    counts.set(height, (counts.has(height) ? counts.get(height)! : 0) + 1);\n}\nconst expected: Array<number> = [];\nfor (const height of counts.keys()) {\n    for (let i = 0; i < counts.get(height)!; i++) {\n        expected.push(height);\n    }\n}\nlet mismatches = 0;\nfor (let i = 0; i < heights.length; i++) {\n    if (heights[i] !== expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":14,"12":17},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"11":{"startLine":14,"endLine":16}},"alternateStyles":{"close-to-source":{"code":"const counts: Map<number, number> = new Map();\nfor (const height of heights) {\n    counts.set(height, (counts.has(height) ? counts.get(height)! : 0) + 1);\n}\nconst expected: Array<number> = [];\nfor (const height of counts.keys()) {\n    const end = counts.get(height);\n    if (end === undefined) throw new Error(\"KeyError\");\n    for (let i = 0; i < end; i++) {\n        expected.push(height);\n    }\n}\nlet mismatches = 0;\nfor (let i = 0; i < heights.length; i++) {\n    if (heights[i] !== expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":10,"8":13,"9":14,"10":15,"11":16,"12":19},"statementBundles":{"3":{"startLine":3,"endLine":4},"6":{"startLine":7,"endLine":9},"7":{"startLine":10,"endLine":12},"11":{"startLine":16,"endLine":18}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"Map<Integer, Integer> counts = new HashMap<Integer, Integer>();\nfor (Integer height : heights) {\n    counts.put(height, (counts.getOrDefault(height, 0) + 1));\n}\nList<Integer> expected = new ArrayList<>();\nfor (Integer height : counts.keySet()) {\n    for (int i = 0; i < counts.get(height); i++) {\n        expected.add(height);\n    }\n}\nint mismatches = 0;\nfor (int i = 0; i < heights.size(); i++) {\n    if (heights.get(i) != expected.get(i)) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":14,"12":17},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"11":{"startLine":14,"endLine":16}},"alternateStyles":{"close-to-source":{"code":"Map<Integer, Integer> counts = new HashMap<Integer, Integer>();\nfor (Integer height : heights) {\n    counts.put(height, (counts.getOrDefault(height, 0) + 1));\n}\nList<Integer> expected = new ArrayList<>();\nfor (Integer height : counts.keySet()) {\n    for (int i = 0; i < requireMapValue(counts, height); i++) {\n        expected.add(height);\n    }\n}\nint mismatches = 0;\nfor (int i = 0; i < heights.size(); i++) {\n    if (heights.get(i) != expected.get(i)) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":14,"12":17},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"11":{"startLine":14,"endLine":16}}}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"Dictionary<int, int> counts = new();\nforeach (int height in heights) {\n    counts[height] = (counts.ContainsKey(height) ? counts[height] : 0) + 1;\n}\nList<int> expected = new();\nforeach (int height in counts.Keys) {\n    for (int i = 0; i < counts[height]; i++) {\n        expected.Add(height);\n    }\n}\nint mismatches = 0;\nfor (int i = 0; i < heights.Count; i++) {\n    if (heights[i] != expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":14,"12":17},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"11":{"startLine":14,"endLine":16}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"unordered_map<int, int> counts;\nfor (int height : heights) {\n    counts[height] += 1;\n}\nvector<int> expected;\nfor (const auto& [height, value] : counts) {\n    for (int i = 0; i < counts.at(height); i++) {\n        expected.push_back(height);\n    }\n}\nint mismatches = 0;\nfor (int i = 0; i < heights.size(); i++) {\n    if (heights[i] != expected[i]) {\n        mismatches++;\n    }\n}\nreturn mismatches;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11,"9":12,"10":13,"11":14,"12":17},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10},"11":{"startLine":14,"endLine":16}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"A line already in order, a line where students share a height, and a line where every height is identical. Any one can expose extra branching.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"arrays":[{"name":"already in order","values":[1,2,3,4,5]},{"name":"shared heights","values":[1,3,2,2,4,4]},{"name":"all identical","values":[2,2,2]}]}}]},"body":["A line already in nondecreasing order, a line where several students share a height, and a line where every student is the same height.","Each looks like it might need a branch of its own. The probes that follow decide whether any actually does."]},{"id":"already-sorted-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does an already-ordered line return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"already-sorted-state","state":{"nums":[1,2,3,4,5],"i":2,"seen":{"1":1,"2":1,"3":1,"4":1,"5":1},"labels":{"nums":"heights","seen":"counts"}}}]},"summary":"heights = [1, 2, 3, 4, 5], already nondecreasing.","options":[{"id":"zero","label":"0, because every position already matches the expected order","rationale":"The replay rebuilds [1, 2, 3, 4, 5], identical to the input, so no position differs.","isCorrect":true},{"id":"five","label":"5, because the line gets sorted","rationale":"Sorting an already-ordered line changes nothing, so the compared positions all match.","isCorrect":false},{"id":"needs-guard","label":"It needs an early check for a sorted line","rationale":"The same tally-replay-compare returns 0 here without any guard.","isCorrect":false}],"answer":"The expected line equals the input, so every position matches and the count stays 0. No special check is needed."},{"id":"duplicates-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Where do the shared heights differ from the sorted order?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"duplicates-state","state":{"rows":[{"label":"heights","values":[1,3,2,2,4,4],"changed":[1,3]},{"label":"expected","values":[1,2,2,3,4,4],"changed":[1,3]}]}}]},"summary":"heights = [1, 3, 2, 2, 4, 4], expected order [1, 2, 2, 3, 4, 4].","options":[{"id":"two-positions","label":"Positions 1 and 3 differ, so it returns 2","rationale":"Index 1 holds 3 against expected 2 and index 3 holds 2 against expected 3; the duplicate 2s and 4s sit where they belong.","isCorrect":true},{"id":"all-duplicates","label":"Every position with a duplicate height differs","rationale":"The two 4s land in their sorted spots and never count; only the displaced 3 and one 2 differ.","isCorrect":false},{"id":"dups-need-branch","label":"Shared heights need their own special case","rationale":"Replaying each height count times places duplicates correctly with no extra branch.","isCorrect":false}],"answer":"Only indices 1 and 3 differ, for 2. The replay emits each 2 and each 4 in its sorted place, so duplicates need no branch."},{"id":"all-identical-info","chapter":"Edge cases","kind":"info","eyebrow":"Rule out a special case","title":"Identical heights need no cleanup","summary":"A line of one repeated height looks like it might trip the replay. It sorts to itself.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"identical-state","state":{"nums":[2,2,2],"i":1,"seen":{"2":3},"labels":{"nums":"heights","seen":"counts"}}}]},"body":["For heights = [2, 2, 2]: the tally is 2: 3, and replaying it emits 2 three times, giving the expected line [2, 2, 2].","The expected line equals the input, so every position matches and the compare pass returns 0, through the same three stages."]},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Two passes build the expected line, and one compare pass counts what moved.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[1,1,4,2,1,3],"seen":{"1":3,"2":1,"3":1,"4":1},"labels":{"nums":"heights","seen":"counts"}}}]},"body":["Tally each height into per-height counts, replay them low to high into a fresh expected line, then walk both lines together and count the positions where the original height differs from the expected one."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the count-and-compare check","summary":"Now turn the count-and-compare into code: create the count map and tally every height, start a fresh expected line and replay the counts low to high, then walk both lines and return how many positions differ.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","body":["Height Checker is a sort in disguise, and the disguise is the bounded value range. Because every height is a small integer, counting beats comparing.","Replay the counts from the lowest height upward into a fresh expected line, so the compare has the sorted order on one side and the original on the other."],"takeaways":[{"title":"Bounded values mean count, not compare","body":"Heights between 1 and 100 let one tally pass and one replay pass build sorted order in O(n + k), below the comparison sort O(n log n)."},{"title":"Replay multiplicity, not membership","body":"Each height enters the expected line as many times as its count, so duplicates land in their own sorted positions."},{"title":"Replay from the lowest height upward","body":"The expected line is sorted only when the counts are emitted in increasing height order; walking the count map in the order its keys arrived leaves the expected line out of order."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
