{"id":"how-many-numbers-are-smaller-than-current","title":"How Many Numbers Are Smaller Than the Current Number","difficulty":"easy","patterns":["sorting-linear"],"primaryConcept":"sorting-linear","concepts":["sorting-linear"],"problemForm":"intro","companies":["Amazon","Google","Meta","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"array-length","constraints":["non-negative","bounded-values"],"sizes":[8,16,32,64],"valueRange":{"min":0,"max":100}},"description":"Given an array `nums`, return an array `answer` where `answer[i]` is the number of elements in `nums` that are strictly smaller than `nums[i]`.\n\nFor this TraceCode exercise, use the bounded value range `0..100` to count frequencies and build prefix counts in linear time. Do not comparison-sort the array.","requiredComplexity":[{"metric":"time","bound":"O(n)","scope":"function","functions":["smallerNumbersThanCurrent"],"case":"worst","enforcement":"hard","reason":"The solution scans nums and the fixed value range 0..100, so the bounded-range pass is constant relative to input size."}],"examples":[{"input":"nums = [8,1,2,2,3]","output":"[4,0,1,1,3]","explanation":"There are four numbers smaller than 8, none smaller than 1, one smaller than each 2, and three smaller than 3."},{"input":"nums = [6,5,4,8]","output":"[2,1,0,3]","explanation":"The sorted order would be 4, 5, 6, 8, but prefix counts let us answer without sorting nums."}],"constraints":[{"id":"1-len-nums-500","text":"1 <= len(nums) <= 500","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":500}},{"id":"0-nums-i-100","text":"0 <= nums[i] <= 100","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":0,"max":100}}],"starterCode":"class Solution:\n    def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:\n        # Your code here\n        pass","functionName":"smallerNumbersThanCurrent","testCases":[{"id":"1","input":{"nums":[8,1,2,2,3]},"expected":[4,0,1,1,3],"description":"Classic sample with duplicates."},{"id":"2","input":{"nums":[6,5,4,8]},"expected":[2,1,0,3],"description":"Distinct values in descending-adjacent order."},{"id":"3","input":{"nums":[7,7,7,7]},"expected":[0,0,0,0],"description":"Equal values are not strictly smaller than each other."},{"id":"4","input":{"nums":[0,100,50]},"expected":[0,2,1],"description":"Both endpoints of the bounded value range are valid."},{"id":"5","input":{"nums":[5]},"expected":[0],"description":"A single value has no smaller peer."},{"id":"hidden-1","input":{"nums":[1,2,3,4]},"expected":[0,1,2,3],"description":"Already ascending values."},{"id":"hidden-2","input":{"nums":[4,3,2,1]},"expected":[3,2,1,0],"description":"Descending values."},{"id":"hidden-3","input":{"nums":[2,0,2,0]},"expected":[2,0,2,0],"description":"Two duplicated groups."},{"id":"hidden-4","input":{"nums":[100,0,100,50,50]},"expected":[3,0,3,1,1],"description":"The maximum value appears twice and middle values tie."},{"id":"hidden-5","input":{"nums":[9,1,9,5,3]},"expected":[3,0,3,2,1],"description":"Mixed duplicates and gaps in the value range."}],"hints":[{"level":1,"content":"You do not need to compare every pair. Count how many times each value appears."},{"level":2,"content":"When you scan values from low to high, the running total before value x is exactly how many numbers are smaller than x."},{"level":3,"content":"Build a lookup smaller[value] from prefix counts, then map every original number through that lookup.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"how-many-numbers-are-smaller-than-current-2026-11-20-tally-and-running-total","approachSelection":{"contract":"approach-selection-v1","question":"Which plan does the least work on a list of 500 numbers?","decisionPrompt":"The list holds up to 500 numbers, each from 0 to 100.","approaches":[{"id":"pairwise-count","name":"Scan the whole list for every number","summary":"For each position, walk the list and count the smaller numbers.","decisionReason":"This is the direct scan. On 500 numbers it makes 250,000 comparisons, and equal numbers repeat the same scan.","complexity":{"time":"O(n^2)","space":"O(n)"},"tradeoffs":["One full scan per number: 250,000 comparisons for a list of 500."],"isOptimal":false},{"id":"sort-with-indices","name":"Sort a copy, then look each number up","summary":"Sort the numbers. A value's answer is how many entries come before its first appearance.","decisionReason":"Sorting 500 numbers takes at most a few thousand comparisons, O(n log n), and it orders the whole list when the task needs only one answer for each of 101 values.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Sorting sets the cost at O(n log n), and it needs a sorted copy plus a way back from each number to its place."],"isOptimal":false},{"id":"prefix-counts","name":"Tally each value, then total the tallies","summary":"Count how many times each value from 0 to 100 appears, then work out every answer from those 101 tallies.","decisionReason":"One pass over the list fills the tallies, and the answers then come from 101 tallies instead of 250,000 comparisons.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Linear in the length of the list, plus a fixed pass over the 101 possible values. It depends on the values being bounded."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-counts","title":"Create the tally table","description":"Start an empty table that will map each value to how many times it appears.","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 table before scanning nums.","doneWhen":"This step is done when an empty keyed state exists for value counts.","shouldFailWhen":"This step should fail if no count structure is created or if values are hard-coded.","roles":["frequency table","value","count"],"mustProve":["The code initializes a keyed state for counts.","The keyed state exists before the counting scan."],"mustNotAccept":["Sorting nums instead of building counts.","Using fixed counts from an example."],"equivalentVariants":["Use a dictionary or map keyed by value.","Use another keyed frequency structure."],"proofSnippets":[{"id":"py-smaller-current-init-counts","language":"python","code":"class Solution:\n    def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:\n        counts = {}\n        return []"}]},"commonMistakes":["Creating the table inside the loop over the list, which empties it for every number"],"hint":"Values run from 0 to 100, so a table of 101 slots works as well as a map."},{"id":"count-values","title":"Tally every number","description":"Walk the list once and add 1 to the tally for each number's 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 how many times each value appears in nums.","doneWhen":"This step is done when the code loops over nums and increments the count keyed by the current number.","shouldFailWhen":"This step should fail if duplicate values overwrite each other or if nums is not scanned.","roles":["nums","current number","frequency update"],"mustProve":["The code scans nums.","The current number is used as the key for an incrementing count."],"mustNotAccept":["Assigning every count to 1.","Counting indexes instead of values."],"equivalentVariants":["Use counts[num] = counts.get(num, 0) + 1.","Use any equivalent map counter update."],"proofSnippets":[{"id":"py-smaller-current-count-values","language":"python","code":"class Solution:\n    def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        return []"}]},"commonMistakes":["Setting the tally to 1 on every visit, which loses repeats: two 2s would tally as one","Tallying positions instead of the numbers stored at them"],"hint":"A value met for the first time has no tally yet, so its tally starts from 0."},{"id":"init-running","title":"Start the running total at zero","description":"Before the pass over the values, create the second table for the answers and set the running total to 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_zero_accumulator","scope":"init-total","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Prepare a zero running total before scanning bounded values from low to high.","doneWhen":"This step is done when a numeric accumulator starts at zero before the range scan.","shouldFailWhen":"This step should fail if the running total starts from a count value or is reset inside the range loop.","roles":["running total","smaller values","prefix scan"],"mustProve":["The code initializes a numeric accumulator to zero.","The accumulator is available before the bounded value scan."],"mustNotAccept":["Starting running from len(nums).","Resetting running for every value."],"equivalentVariants":["Use running = 0.","Use any zero-seeded numeric state for prefix counts."],"proofSnippets":[{"id":"py-smaller-current-init-running","language":"python","code":"class Solution:\n    def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        smaller = {}\n        running = 0\n        return []"}]},"commonMistakes":["Resetting the total inside the pass over the values, so it never accumulates"],"hint":"Nothing has been passed before value 0, so nothing is smaller yet."},{"id":"build-prefix-counts","title":"Turn the tallies into answers","description":"Go through the values 0 through 100 in order. For each one, store the running total as that value's answer in a second table, then add the value's tally to the total.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"builds_strict_prefix_count_lookup","scope":"build-prefix-counts","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Turn frequencies into prefix counts where smaller[value] is the number of input values below value.","doneWhen":"This step is done when the bounded value scan stores the current running total, then adds the current value's frequency.","shouldFailWhen":"This step should fail if equal values are included as smaller or if the running total is not accumulated.","roles":["bounded value","running total","smaller-count lookup"],"mustProve":["The code scans possible values in ascending order.","The current running total is stored for a value before that value's own frequency is added.","The running total is increased by each value's frequency."],"mustNotAccept":["Adding the current value before storing smaller[value].","Comparing every pair instead of using prefix counts."],"equivalentVariants":["Store smaller[value] = running, then running += counts[value].","Use an equivalent prefix-count table over the bounded range."],"proofSnippets":[{"id":"py-smaller-current-build-prefix-counts","language":"python","code":"class Solution:\n    def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        smaller = {}\n        running = 0\n        for value in range(101):\n            smaller[value] = running\n            running += counts.get(value, 0)\n        return []"}]},"commonMistakes":["Adding the tally before storing, which makes every number count its own copies","Stopping at 99, so a 100 in the list has no answer to look up","Reading the tally of a value that never appeared without falling back to 0"],"hint":"A value that never appeared has no tally, and adds 0."},{"id":"init-result","title":"Start the output list","description":"Create an empty list for the output, separate from the two tables.","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 result sequence for answers in original input order.","doneWhen":"This step is done when the code initializes a mutable result sequence after the lookup is built.","shouldFailWhen":"This step should fail if the code returns the lookup directly or never builds an output sequence.","roles":["result array","original order","smaller-count lookup"],"mustProve":["The code initializes a result sequence.","The result sequence is distinct from the lookup table."],"mustNotAccept":["Returning the frequency map.","Returning smaller in value order instead of nums order."],"equivalentVariants":["Use an empty list.","Use another mutable sequence for output."],"proofSnippets":[{"id":"py-smaller-current-init-result","language":"python","code":"class Solution:\n    def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        smaller = {}\n        running = 0\n        for value in range(101):\n            smaller[value] = running\n            running += counts.get(value, 0)\n        result = []\n        return []"}]},"commonMistakes":[],"hint":"The output has one entry for each position of the input, in the same order."},{"id":"build-result","title":"Look up every number","description":"Walk the input again in its original order. For each number, add its stored answer to the end of the output.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"builds_projected_result_sequence","scope":"convert-index","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Build answer[i] by looking up how many values are smaller than nums[i].","doneWhen":"This step is done when the code scans nums and appends smaller[num] to the result.","shouldFailWhen":"This step should fail if the output is built in value order or if it appends the original number instead of its smaller count.","roles":["current number","smaller-count lookup","projected result"],"mustProve":["The code scans nums in original order.","The code appends a lookup-derived count for each scanned number."],"mustNotAccept":["Appending num itself.","Appending counts[num] instead of smaller[num]."],"equivalentVariants":["Append smaller[num] inside a loop over nums.","Use a comprehension or map that projects every num through the smaller-count lookup."],"proofSnippets":[{"id":"py-smaller-current-build-result","language":"python","code":"class Solution:\n    def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        smaller = {}\n        running = 0\n        for value in range(101):\n            smaller[value] = running\n            running += counts.get(value, 0)\n        result = []\n        for num in nums:\n            result.append(smaller[num])\n        return []"}]},"commonMistakes":["Adding the tally of the number instead of its stored answer","Walking the values in increasing order instead of the input, which returns the answers sorted"],"hint":"Each number's answer was stored under its value."},{"id":"return-result","title":"Return the output list","description":"Return the list that holds one answer for each input position.","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 projected answer array after every original number has been handled.","doneWhen":"This step is done when the function returns the same result sequence that received appended lookup values.","shouldFailWhen":"This step should fail if the code returns counts, smaller, or a scalar.","roles":["result array","projected counts","return value"],"mustProve":["The returned sequence is the populated result.","The returned sequence was produced by append or projection operations."],"mustNotAccept":["Returning the frequency table.","Returning the smaller lookup table."],"equivalentVariants":["Return result.","Return an equivalent projected answer sequence."],"proofSnippets":[{"id":"py-smaller-current-return-result","language":"python","code":"class Solution:\n    def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:\n        counts = {}\n        for num in nums:\n            counts[num] = counts.get(num, 0) + 1\n        smaller = {}\n        running = 0\n        for value in range(101):\n            smaller[value] = running\n            running += counts.get(value, 0)\n        result = []\n        for num in nums:\n            result.append(smaller[num])\n        return result"}]},"commonMistakes":["Returning the table of answers by value instead of the output list"],"hint":"The two tables were working storage. The output list is the result."}],"slides":[{"id":"read-the-signal","kind":"info","title":"For every number, count the smaller ones","workspacePanel":"problem","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,0,1,1,3]}]}}]},"body":["You get a list of numbers, each between 0 and 100. For every position, work out how many numbers in the list are strictly smaller than the number there. Return those results in the same order as the list.","The drawing shows one list with its answer underneath. Four of its numbers are smaller than 8, so the 8 gets 4. Each 2 gets 1: only the 1 is smaller, and an equal number does not count."]},{"id":"brute-force","kind":"code-trace","title":"The direct way scans the whole list for every number","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"answer = [0] * len(nums)\nfor i in range(len(nums)):\n    count = 0\n    for j in range(len(nums)):\n        if nums[j] < nums[i]:\n            count += 1\n    answer[i] = count","steps":[{"id":"scan-eight","title":"8 is compared with all five numbers","summary":"1, 2, 2 and 3 are smaller than 8, so `count` reaches 4.","codeLine":5,"state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":["·","·","·","·","·"]}],"i":0,"count":4}},{"id":"write-eight","title":"4 goes into the answer under the 8","summary":"That one answer cost five comparisons.","codeLine":7,"state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,"·","·","·","·"],"changed":[0]}],"i":0,"count":4}},{"id":"scan-one","title":"1 takes five more comparisons","summary":"Nothing in the list is smaller than 1, so it gets 0.","codeLine":7,"state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,0,"·","·","·"],"changed":[1]}],"i":1,"count":0}},{"id":"scan-first-two","title":"The first 2 takes five more","summary":"Only the 1 is smaller, so this 2 gets 1.","codeLine":7,"state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,0,1,"·","·"],"changed":[2]}],"i":2,"count":1}},{"id":"scan-second-two","title":"The second 2 repeats the same five comparisons","summary":"It meets the same numbers as the first 2 and ends on the same 1.","codeLine":7,"state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,0,1,1,"·"],"changed":[3]}],"i":3,"count":1}},{"id":"scan-three","title":"3 finishes the answer","summary":"1, 2 and 2 are smaller than 3, so it gets 3. Five numbers took 25 comparisons.","codeLine":7,"state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,0,1,1,3],"changed":[4]}],"i":4,"count":3}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const answer = Array(nums.length).fill(0);\nfor (let i = 0; i < nums.length; i++) {\n    let count = 0;\n    for (let j = 0; j < nums.length; j++) {\n        if (nums[j] < nums[i]) {\n            count++;\n        }\n    }\n    answer[i] = count;\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const answer = Array(nums.length).fill(0);\nfor (let i = 0; i < nums.length; i++) {\n    let count = 0;\n    for (let j = 0; j < nums.length; j++) {\n        if (nums[j] < nums[i]) {\n            count++;\n        }\n    }\n    answer[i] = count;\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int[] answer = new int[nums.size()];\nfor (int i = 0; i < nums.size(); i++) {\n    int count = 0;\n    for (int j = 0; j < nums.size(); j++) {\n        if (nums.get(j) < nums.get(i)) {\n            count++;\n        }\n    }\n    answer[i] = count;\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> answer = Enumerable.Repeat<int>(0, nums.Count).ToList();\nfor (int i = 0; i < nums.Count; i++) {\n    int count = 0;\n    for (int j = 0; j < nums.Count; j++) {\n        if (nums[j] < nums[i]) {\n            count++;\n        }\n    }\n    answer[i] = count;\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> answer = vector<int>(nums.size(), 0);\nfor (int i = 0; i < nums.size(); i++) {\n    int count = 0;\n    for (int j = 0; j < nums.size(); j++) {\n        if (nums[j] < nums[i]) {\n            count++;\n        }\n    }\n    answer[i] = count;\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}}}},"body":["For each position, this code walks the entire list and counts the numbers that are smaller."]},{"id":"waste-probe","kind":"case-probe","title":"Five numbers took 25 comparisons. How many does a list of 500 numbers take?","workspacePanel":"trace","options":[{"id":"per-number","label":"500, one for each number","rationale":"One comparison per number would be a single pass. The direct scan makes a full pass of 500 for each of the 500 numbers.","isCorrect":false},{"id":"every-pair-once","label":"124,750, one for each pair of numbers","rationale":"That counts each pair once. The direct scan compares every number with all 500, so each pair is checked in both directions and every number is checked against itself.","isCorrect":false},{"id":"full-square","label":"250,000, a full pass of 500 for each number","rationale":"Each of the 500 numbers is compared with all 500, itself included: 500 × 500.","isCorrect":true}]},{"id":"duplicate-probe","kind":"case-probe","title":"Another 8 joins the end of the list. What answer does it get?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"second-eight","state":{"rows":[{"label":"nums","values":[8,1,2,2,3,8]},{"label":"answer","values":[4,0,1,1,3,"?"]}],"i":5}}]},"options":[{"id":"same-as-first","label":"4, the same as the first 8","rationale":"The new 8 has the same four numbers below it as the first one: 1, 2, 2 and 3. Within one list, a number's answer depends only on its value. Values stop at 100, so even 500 numbers have at most 101 different answers.","isCorrect":true},{"id":"counts-other-eight","label":"5, because the first 8 now counts too","rationale":"An equal number is not strictly smaller. Neither 8 counts the other.","isCorrect":false},{"id":"nothing-after","label":"0, because nothing comes after it","rationale":"An answer looks at the whole list, in both directions. Where a number sits makes no difference.","isCorrect":false}]},{"id":"approach-selection","kind":"choice","source":"approach-selection","title":"Which plan does the least work on a list of 500 numbers?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,0,1,1,3]}]}}]}},{"id":"idea-bridge","kind":"info","title":"One pass over the list fills the tallies","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"tally-eight","title":"8 gets a tally of 1","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]}],"i":0,"arrays":[{"name":"counts","values":["·","·","·","·","·","·","·","·",1],"current":8}]}},{"id":"tally-one","title":"1 gets a tally of 1","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]}],"i":1,"arrays":[{"name":"counts","values":["·",1,"·","·","·","·","·","·",1],"current":1}]}},{"id":"tally-first-two","title":"The first 2 gets a tally of 1","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]}],"i":2,"arrays":[{"name":"counts","values":["·",1,1,"·","·","·","·","·",1],"current":2}]}},{"id":"tally-second-two","title":"The second 2 raises that tally to 2","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]}],"i":3,"arrays":[{"name":"counts","values":["·",1,2,"·","·","·","·","·",1],"current":2}]}},{"id":"tally-three","title":"3 gets a tally of 1","summary":"Five numbers are now four tallies: one 1, two 2s, one 3 and one 8.","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]}],"i":4,"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1],"current":3}]}}]},"body":["Keep a table called `counts` that holds a tally for each value: how many times that value has appeared so far. Walk the list once and add 1 to the tally of each number you meet.","The drawing shows `counts` for the values 0 through 8. A dot marks a value with no tally."]},{"id":"prefix-probe","kind":"case-probe","title":"Using only `counts`, how many numbers in the list are smaller than 3?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"counts-at-three","state":{"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1],"current":3}]}}]},"options":[{"id":"values-below","label":"2, the number of tallies below 3","rationale":"Two different values sit below 3, but the list holds three numbers there, because the 2 appears twice.","isCorrect":false},{"id":"sum-below","label":"3, the sum of the tallies below 3","rationale":"The numbers smaller than 3 are the one 1 and the two 2s: 1 + 2. Store that 3 in a second table, `smaller`, under the value 3.","isCorrect":true},{"id":"sum-through","label":"4, the sum of the tallies up to and including 3","rationale":"1 + 2 + 1 also counts the 3 itself, and a 3 is not smaller than 3.","isCorrect":false}]},{"id":"running-probe","kind":"case-probe","title":"`smaller` holds 3 for the value 3. What is the cheapest way to get the answer for 4?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"smaller-at-three","state":{"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1]},{"name":"smaller","values":["·","·","·",3,"·","·","·","·","·"],"current":4}]}}]},"options":[{"id":"add-tally-of-three","label":"Add the tally of 3 to the answer for 3","rationale":"Every number below 3 is also below 4, and the only new ones are the 3s. That gives 3 + 1 = 4.","isCorrect":true},{"id":"add-tally-of-four","label":"Add the tally of 4 to the answer for 3","rationale":"The 4s are not smaller than 4. Here the value 4 has no tally at all, so this would leave the answer at 3.","isCorrect":false},{"id":"sum-again","label":"Add up the tallies of 0, 1, 2 and 3 again","rationale":"That reaches 4 as well, but it repeats the additions already done for 3. By value 100 it would add up 100 tallies for a single answer.","isCorrect":false}]},{"id":"dry-run-setup","kind":"info","title":"One pass through the values fills `smaller`","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"value-zero","title":"Value 0 stores 0","summary":"Nothing has been passed yet, and 0 has no tally to add.","state":{"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1],"current":0},{"name":"smaller","values":[0,"·","·","·","·","·","·","·","·"],"current":0}],"running":0}},{"id":"value-one","title":"Value 1 stores 0, then adds its tally","summary":"No number in the list is smaller than 1. After the add, `running` is 1.","state":{"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1],"current":1},{"name":"smaller","values":[0,0,"·","·","·","·","·","·","·"],"current":1}],"running":1}}]},"body":["The same step works at every value: the next value's answer is this value's answer plus this value's tally.","So the pass carries one number, `running`: the total of the tallies of every value below the one the pass has reached. Go through the values from 0 upward and store `running` as each value's answer."]},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Continue the pass from value 2","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"at-two","state":{"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1],"current":2},{"name":"smaller","values":[0,0,"·","·","·","·","·","·","·"],"current":2}],"running":1}},{"id":"at-three","state":{"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1],"current":3},{"name":"smaller","values":[0,0,1,"·","·","·","·","·","·"],"current":3}],"running":3}},{"id":"at-five","state":{"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1],"current":5},{"name":"smaller","values":[0,0,1,3,4,"·","·","·","·"],"current":5}],"running":4}},{"id":"finished","state":{"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1],"current":8},{"name":"smaller","values":[0,0,1,3,4,4,4,4,4],"current":8}],"running":5}}]},"beats":[{"id":"store-for-two","title":"The pass reaches value 2 with `running` at 1. What does it store for 2, and what is the total afterwards?","summary":"","prompt":"","options":[{"id":"store-one","label":"It stores 1, then the total becomes 3","rationale":"One number, the 1, is smaller than 2. The two 2s join the total only after the answer for 2 is stored.","isCorrect":true},{"id":"store-three","label":"It stores 3, and the total stays at 3","rationale":"That adds the two 2s before storing, so each 2 would count itself and the other 2 as smaller.","isCorrect":false},{"id":"store-two","label":"It stores 2, then the total becomes 3","rationale":"2 is the tally of 2: how many 2s the list holds. The answer for 2 is the total passed before reaching it.","isCorrect":false}]},{"id":"store-for-four","title":"Value 3 is next, then value 4, which has no tally. What does the pass store for 4?","summary":"","prompt":"","options":[{"id":"four","label":"4, the total once the tally of 3 is added","rationale":"The pass stores 3 for value 3 and then adds its tally of 1. All four of 1, 2, 2 and 3 are smaller than 4.","isCorrect":true},{"id":"three","label":"3, the same as value 3","rationale":"3 is stored for value 3 before its own tally is added. By the time the pass reaches 4, `running` has grown by that tally.","isCorrect":false},{"id":"zero","label":"0, because 4 is not in the list","rationale":"A value with no tally adds nothing to `running`, but it still receives the total so far.","isCorrect":false}]},{"id":"store-for-eight","title":"Values 5, 6 and 7 have no tally either. What does the pass store for 8?","summary":"","prompt":"","options":[{"id":"four","label":"4, unchanged since value 4","rationale":"Three values with no tally add nothing, so `running` is still 4 when the pass reaches 8. The direct scan found the same four numbers below 8: 1, 2, 2 and 3.","isCorrect":true},{"id":"five","label":"5, counting the 8 itself","rationale":"The tally of 8 is added after the answer for 8 is stored. 5 is what `running` holds once the pass moves on.","isCorrect":false},{"id":"seven","label":"7, one more for each value passed","rationale":"`running` grows by tallies. Passing a value that the list does not contain adds nothing.","isCorrect":false}]}]},{"id":"read-back","kind":"dry-run","source":"trace-example","title":"Read the answer out of `smaller`","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-read","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":["·","·","·","·","·"]}],"arrays":[{"name":"smaller","values":[0,0,1,3,4,4,4,4,4]}]}},{"id":"after-read","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,0,1,1,3],"changed":[0,1,2,3,4]}],"arrays":[{"name":"smaller","values":[0,0,1,3,4,4,4,4,4]}]}}]},"beats":[{"id":"read-in-list-order","title":"Walk the list in its original order and look each number up in `smaller`. What comes out?","summary":"","prompt":"","options":[{"id":"sorted-order","label":"0, 1, 1, 3, 4","rationale":"Those are the right numbers in sorted order. The answer has to line up with the list, which starts with 8.","isCorrect":false},{"id":"list-order","label":"4, 0, 1, 1, 3","rationale":"8 looks up 4, 1 looks up 0, each 2 looks up 1, and 3 looks up 3. Each result lands at its number's position. Five lookups gave the same row that took the direct scan 25 comparisons.","isCorrect":true},{"id":"tallies","label":"1, 1, 2, 2, 1","rationale":"Those are the tallies from `counts`: how many times each number's value appears. How many numbers sit below each value is in `smaller`.","isCorrect":false}]}]},{"id":"edge-case-intro","kind":"info","title":"The example had one repeat and values from 1 to 8. Next, two other lists.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"finished-example","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,0,1,1,3]}],"arrays":[{"name":"smaller","values":[0,0,1,3,4,4,4,4,4]}]}}]},"body":["In the first, every number is the same. The second holds both 0 and 100, the smallest and largest values allowed.","Does the same pass give the right answer on each?"]},{"id":"all-equal-edge","kind":"case-probe","title":"In the first list, every number is 7. What does each position get?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-sevens","state":{"rows":[{"label":"nums","values":[7,7,7]},{"label":"answer","values":["?","?","?"]}],"arrays":[{"name":"counts","values":["·","·","·","·","·","·","·",3]}]}}]},"options":[{"id":"zero","label":"0, because nothing is below 7","rationale":"`running` is still 0 when the pass reaches 7, and that 0 is stored before the tally of 3 is added.","isCorrect":true},{"id":"two","label":"2, the other two 7s","rationale":"An equal number is not strictly smaller, so no 7 counts another 7.","isCorrect":false},{"id":"three","label":"3, the tally of 7","rationale":"3 would be stored only if the tally were added before the answer. The pass stores first, so the 7s never count themselves.","isCorrect":false}]},{"id":"zero-edge","kind":"case-probe","title":"The second list is 0, 100, 50. Where does the pass over the values have to start and stop so that every lookup finds an entry?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"both-ends","state":{"rows":[{"label":"nums","values":[0,100,50]},{"label":"answer","values":[0,2,1]}]}}]},"options":[{"id":"skip-zero","label":"1 through 100, which is 100 values","rationale":"The 0 in the list would look up an entry that was never stored.","isCorrect":false},{"id":"full-range","label":"0 through 100, which is 101 values","rationale":"The 0 looks up the entry for 0 and the 100 looks up the entry for 100, so the pass has to store both.","isCorrect":true},{"id":"stop-early","label":"0 through 99, which is 100 values","rationale":"The pass would end before storing an answer for 100, and the 100 in the list would find nothing.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"With every piece of the plan in place, the function comes next.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"finished-example","state":{"rows":[{"label":"nums","values":[8,1,2,2,3]},{"label":"answer","values":[4,0,1,1,3]}],"arrays":[{"name":"counts","values":["·",1,2,1,"·","·","·","·",1]},{"name":"smaller","values":[0,0,1,3,4,4,4,4,4]}]}}]},"body":["The function first walks the list once and tallies how many times each value appears.","Then it goes through the values from 0 to 100 in order, keeping a running total that starts at 0. At each value, it stores the total as that value's answer, then adds the value's tally to the total.","Last, it walks the list again in its original order, looks up each number's answer, and returns those answers in the same order."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Tally, total, then look each number up","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"From 250,000 comparisons to three passes","workspacePanel":"code","takeaways":[{"title":"An answer depends only on the value","body":"Equal numbers have the same numbers below them, so the work is one answer per value, at most 101 of them, however long the list is."},{"title":"A running total fills every answer in one pass","body":"Going through the values from 0 upward, the total of the tallies passed so far is the answer for the value the pass has just reached."},{"title":"Store the total, then add the tally","body":"Storing first keeps a value's own copies out of its answer, which is why 7, 7, 7 returns 0, 0, 0."},{"title":"Linear time and little extra space","body":"The list is read twice and the 101 values once, so the time is O(n), against O(n^2) for the direct scan. Beyond the answer itself, the two tables hold at most 101 entries each."}]}],"slidesOrigin":"authored"}}
