{"id":"intersection-of-two-arrays-ii","title":"Intersection of Two Arrays II","difficulty":"easy","patterns":["hash-map"],"primaryConcept":"hash-map-grouping","concepts":["hash-map-grouping"],"problemForm":"core","companies":["Amazon","Google","Microsoft","Meta"],"category":"hash-tables","executionStyle":"solution-method","compareMode":"unordered-array","syntheticTestConfig":{"inputShape":"two-arrays","primaryParam":"nums1","secondaryParam":"nums2","sizeMetric":"total-length","valueRange":{"min":0,"max":50},"sizes":[8,16,32,64]},"description":"Given two integer arrays `nums1` and `nums2`, return an array of their intersection including multiplicity. Each value should appear in the result as many times as it appears in both arrays. The result can be returned in any order.","examples":[{"input":"nums1 = [1,2,2,1], nums2 = [2,2]","output":"[2,2]","explanation":"The value 2 appears twice in both arrays."},{"input":"nums1 = [4,9,5], nums2 = [9,4,9,8,4]","output":"[4,9]","explanation":"4 and 9 each appear in both arrays at least once."}],"constraints":[{"id":"1-len-nums1-len-nums2-1000","text":"1 <= len(nums1), len(nums2) <= 1000","check":[{"kind":"sizeRange","target":"nums1","measure":"arrayLength","min":1,"max":1000},{"kind":"sizeRange","target":"nums2","measure":"arrayLength","min":1,"max":1000}]},{"id":"0-nums1-i-nums2-i-1000","text":"0 <= nums1[i], nums2[i] <= 1000","check":[{"kind":"valueRange","target":"nums1","selector":"arrayItems","min":0,"max":1000},{"kind":"valueRange","target":"nums2","selector":"arrayItems","min":0,"max":1000}]},{"id":"each-value-in-the-result-should-appear-min-count-in-nums1-count-","text":"Each value in the result should appear min(count in nums1, count in nums2) times"},{"id":"the-result-can-be-returned-in-any-order","text":"The result can be returned in any order"}],"starterCode":"class Solution:\n    def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        # Your code here\n        pass","functionName":"intersect","testCases":[{"id":"1","input":{"nums1":[1,2,2,1],"nums2":[2,2]},"expected":[2,2],"description":"Both copies of 2 are retained."},{"id":"2","input":{"nums1":[4,9,5],"nums2":[9,4,9,8,4]},"expected":[9,4],"description":"Each shared value is limited by the first array count."},{"id":"3","input":{"nums1":[1,2,2,3],"nums2":[2,2,2]},"expected":[2,2],"description":"Result multiplicity is capped by the smaller count."},{"id":"4","input":{"nums1":[1,3,5],"nums2":[2,4,6]},"expected":[],"description":"Disjoint arrays return an empty result."},{"id":"5","input":{"nums1":[0,0,1],"nums2":[0,0,0]},"expected":[0,0],"description":"Zero values are counted like any other key."},{"id":"h1","input":{"nums1":[1000,1000,999],"nums2":[1000,998,1000,1000]},"expected":[1000,1000],"description":"Large duplicate values are capped by nums1."},{"id":"h2","input":{"nums1":[7],"nums2":[7,7]},"expected":[7],"description":"A single available count can be consumed once."},{"id":"h3","input":{"nums1":[2,3,4],"nums2":[5,6,7]},"expected":[],"description":"No overlap."},{"id":"h4","input":{"nums1":[1,1,1],"nums2":[1,1]},"expected":[1,1],"description":"The result is limited by the smaller multiplicity."},{"id":"h5","input":{"nums1":[0,0,0,2],"nums2":[2,0,0]},"expected":[0,0,2],"description":"Zeros are capped by nums2's count, beside a second shared value."}],"hints":[{"level":1,"content":"Unlike the unique intersection problem, duplicate counts matter.","revealPattern":false},{"level":2,"content":"Count values from one array, then consume those counts while scanning the other.","revealPattern":true},{"level":3,"content":"Only append a value when its remaining count is positive, then decrement that count.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"intersection-of-two-arrays-ii-2026-11-20-pairing-to-counts","approachSelection":{"contract":"approach-selection-v1","question":"How should each value of nums2 find its partner in nums1?","decisionPrompt":"Compare how much of nums1 each value has to look at.","approaches":[{"id":"mark-and-search","name":"Search and mark used","summary":"For each value of nums2, walk nums1 for a copy that is not yet used, and mark it.","decisionReason":"It gives the right answer, but each value of nums2 can walk all of nums1, so two lists of 1,000 numbers can mean a million positions looked at.","complexity":{"time":"O(m*n)","space":"O(m)"},"tradeoffs":["No map to build, but the work grows with the product of the two lengths."],"isOptimal":false},{"id":"count-and-consume","name":"Count, then spend","summary":"Count nums1 into a map from each value to its unused copies, then scan nums2 and spend one count for every value kept.","decisionReason":"Each value of nums2 needs one lookup in the map, so the work is one read of each list.","complexity":{"time":"O(m + n)","space":"O(m)"},"tradeoffs":["The map takes one entry for each distinct value in nums1."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-frequency-map","title":"Create the count map","description":"Start an empty map that will hold, for each value, how many unused copies nums1 has.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"initializes_keyed_state","scope":"init-frequency-map","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Using a set, which can say a value is present but cannot say how many copies are left"],"hint":"Create it before either loop, so the counting pass has somewhere to put its totals.","semanticSpec":{"intent":"Initialize keyed count state before counting.","doneWhen":"A map-like structure for value counts exists before any counting runs.","shouldFailWhen":"This step should fail if no keyed state is initialized.","roles":["frequency map"],"mustProve":["The solution initializes keyed state."],"mustNotAccept":["A set-only representation that drops multiplicity."],"proofSnippets":[{"id":"py-intersection-ii-init-frequency-map","language":"python","code":"class Solution:\n    def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        counts = {}"}]}},{"id":"count-first-array","title":"Count nums1","description":"Go through nums1 and add 1 to the count of each value you read.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"counts_items_by_key","scope":"count-frequencies","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Setting the count to 1 every time, which records two copies of a value as one"],"hint":"A value read for the first time has no count yet, so it starts from 0 before the 1 is added.","semanticSpec":{"intent":"Accumulate multiplicity per value in keyed state.","doneWhen":"Each value from the first array raises its count bucket.","shouldFailWhen":"This step should fail if duplicate values do not accumulate.","roles":["current value","frequency map"],"mustProve":["The keyed state counts items by key."],"mustNotAccept":["A write that discards the previous count."],"proofSnippets":[{"id":"py-intersection-ii-count-first-array","language":"python","code":"class Solution:\n    def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        counts = {}\n        for num in nums1:\n            counts[num] = counts.get(num, 0) + 1"}]}},{"id":"scan-second-array","title":"Scan nums2","description":"Loop over every value of nums2. Each one will be checked against the counts.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-candidates","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Placing this loop inside the counting loop, so values are checked against counts that are still being built"],"hint":"This loop starts after the counting loop has finished, so every count is complete before the first check.","semanticSpec":{"intent":"Scan candidate values from an input sequence.","doneWhen":"The solution iterates over the candidate array after the count map has been built.","shouldFailWhen":"This step should fail if only the counted array is scanned.","roles":["second array","current value"],"mustProve":["The traversal reads a candidate sequence separate from the count-building scan."],"mustNotAccept":["A fixed single-position check.","Only scanning the array used to build the counts."],"proofSnippets":[{"id":"py-intersection-ii-scan-second-array","language":"python","code":"class Solution:\n    def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        counts = {}\n        for num in nums1:\n            counts[num] = counts.get(num, 0) + 1\n\n        result = []\n        for num in nums2:\n            pass"}]}},{"id":"check-available-count","title":"Keep a value only if a copy is unused","description":"Look up the current value's count and go on only when it is above zero.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"validates_keyed_lookup_value","scope":"check-available-count","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Testing only whether the value has an entry, when an entry stays in the map after its count reaches zero"],"hint":"A value with no entry has to read as zero here, the same as a value whose copies are all used.","semanticSpec":{"intent":"Guard the append with a keyed lookup on remaining count.","doneWhen":"The solution validates that the keyed lookup value is still positive before keeping a candidate.","shouldFailWhen":"This step should fail if candidates are kept with only key membership or without checking the remaining count.","roles":["current value","frequency map"],"mustProve":["The solution validates the keyed lookup value."],"mustNotAccept":["Membership-only checks that ignore exhausted counts."],"proofSnippets":[{"id":"py-intersection-ii-check-available-count","language":"python","code":"class Solution:\n    def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        counts = {}\n        for num in nums1:\n            counts[num] = counts.get(num, 0) + 1\n\n        result = []\n        for num in nums2:\n            if counts.get(num, 0) > 0:\n                pass"}]}},{"id":"append-match","title":"Add the value to the result","description":"When the count is above zero, add the current value to the result list.","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"}]},"commonMistakes":["Adding the count to the result instead of the value"],"hint":"Create the result list empty before the scan starts. Two lists with nothing in common return it still empty.","semanticSpec":{"intent":"Build the result from matched values.","doneWhen":"The scanned value is added to the result on a successful match.","shouldFailWhen":"This step should fail if matches are never added to the result.","roles":["current value","result sequence"],"mustProve":["The solution appends scan state to the result sequence."],"mustNotAccept":["Adding unrelated state to the result."],"proofSnippets":[{"id":"py-intersection-ii-append-match","language":"python","code":"class Solution:\n    def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        counts = {}\n        for num in nums1:\n            counts[num] = counts.get(num, 0) + 1\n\n        result = []\n        for num in nums2:\n            if counts.get(num, 0) > 0:\n                result.append(num)"}]}},{"id":"consume-count","title":"Spend the copy","description":"After adding the value, lower its count by one.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"updates_keyed_counter_after_lookup_consumption","scope":"consume-count","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Adding the value without lowering its count, which lets every later copy through"],"hint":"Lowering the count before the check would make the last unused copy look used.","semanticSpec":{"intent":"Lower the keyed count after a lookup confirms availability.","doneWhen":"The same count bucket is lowered after the matched value is kept.","shouldFailWhen":"This step should fail if counts are read but never spent.","roles":["current value","frequency map"],"mustProve":["The keyed counter is updated after lookup consumption."],"mustNotAccept":["A solution that never lowers counts."],"proofSnippets":[{"id":"py-intersection-ii-consume-count","language":"python","code":"class Solution:\n    def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        counts = {}\n        for num in nums1:\n            counts[num] = counts.get(num, 0) + 1\n\n        result = []\n        for num in nums2:\n            if counts.get(num, 0) > 0:\n                result.append(num)\n                counts[num] -= 1"}]}},{"id":"return-result","title":"Return the result list","description":"After the scan, return the list of kept values.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning from inside the loop, which hands back the result after the first value"],"hint":"The return comes after the loop over nums2 ends, so every value has had its turn.","semanticSpec":{"intent":"Return the built result sequence.","doneWhen":"The function returns the result sequence after the scan.","shouldFailWhen":"This step should fail if the returned value is not the result sequence.","roles":["result sequence","return value"],"mustProve":["The solution returns result sequence state."],"mustNotAccept":["Returning keyed state instead of the collected values."],"proofSnippets":[{"id":"py-intersection-ii-return-result","language":"python","code":"class Solution:\n    def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        counts = {}\n        for num in nums1:\n            counts[num] = counts.get(num, 0) + 1\n\n        result = []\n        for num in nums2:\n            if counts.get(num, 0) > 0:\n                result.append(num)\n                counts[num] -= 1\n\n        return result"}]}}],"slides":[{"id":"read-the-signal","kind":"info","title":"Find the numbers two lists share, copies included","workspacePanel":"problem","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"task-example","state":{"arrays":[{"name":"nums1","values":[1,2,2,1]},{"name":"nums2","values":[2,3,2,2,1]},{"name":"answer","values":[2,2,1]}]}}]},"body":["You get two lists of numbers. Return a list of the numbers that appear in both, in any order.","If a number repeats in both lists, it repeats in the answer too.","Here the two lists are called nums1 and nums2, and the answer is drawn under them."]},{"id":"copies-probe","kind":"case-probe","title":"nums2 has three 2s. Why does the answer hold only two?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"task-example","state":{"arrays":[{"name":"nums1","values":[1,2,2,1]},{"name":"nums2","values":[2,3,2,2,1]},{"name":"answer","values":[2,2,1]}]}}]},"options":[{"id":"at-most-twice","label":"The answer lists a repeated number at most twice","rationale":"Nothing caps repeats at two. If nums1 also had three 2s, the answer would hold three.","isCorrect":false},{"id":"nums1-runs-out","label":"nums1 has only two 2s, so the third has no partner","rationale":"Each 2 in the answer uses up one 2 from each list. After two, nums1 has none left. The single 1 works the same way: nums2 has only one 1 to pair with nums1's two.","isCorrect":true},{"id":"stops-at-missing","label":"Matching stops at the 3, which nums1 does not have","rationale":"The 1 comes after the 3 in nums2, and it is still in the answer.","isCorrect":false}]},{"id":"brute-force","kind":"code-trace","title":"Pairing the copies off, one value at a time","summary":"One direct way to build the answer: take each value of nums2 in turn, walk nums1 from the start until an unused copy turns up, and mark that copy used.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"used = [False] * len(nums1)\nresult = []\nfor x in nums2:\n    for j in range(len(nums1)):\n        if not used[j] and nums1[j] == x:\n            result.append(x)\n            used[j] = True\n            break","steps":[{"id":"first-two","title":"The first 2 finds a partner at position 1","codeLine":7,"summary":"It looks at 2 positions: the 1 at position 0, then a 2. That 2 is marked used and drawn dimmed, and a 2 goes into result.","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"j":1,"used":[1]},{"name":"nums2","values":[2,3,2,2,1],"i":0,"labels":{"i":"x"}},{"name":"result","values":[2]}]}},{"id":"three-misses","title":"The 3 looks at all 4 positions","codeLine":5,"summary":"nums1 has no 3, and the walk can only learn that by reaching the end. Nothing is added.","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"j":3,"used":[1]},{"name":"nums2","values":[2,3,2,2,1],"i":1,"labels":{"i":"x"}},{"name":"result","values":[2]}]}},{"id":"second-two","title":"The second 2 starts again from position 0","codeLine":7,"summary":"It looks at 3 positions: the 1, the 2 that is already used, and the unused 2 at position 2, which it takes.","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"j":2,"used":[1,2]},{"name":"nums2","values":[2,3,2,2,1],"i":2,"labels":{"i":"x"}},{"name":"result","values":[2,2]}]}},{"id":"third-two","title":"The third 2 looks at all 4 positions","codeLine":5,"summary":"Both 2s in nums1 are used and the last position holds a 1. This 2 finds no partner and stays out of result.","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"j":3,"used":[1,2]},{"name":"nums2","values":[2,3,2,2,1],"i":3,"labels":{"i":"x"}},{"name":"result","values":[2,2]}]}},{"id":"one-matches","title":"The 1 finds a partner at position 0","codeLine":7,"summary":"It looks at 1 position. result now holds 2, 2 and 1, and the 5 values looked at 14 positions between them.","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"j":0,"used":[0,1,2]},{"name":"nums2","values":[2,3,2,2,1],"i":4,"labels":{"i":"x"}},{"name":"result","values":[2,2,1]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const used = Array(nums1.length).fill(false);\nconst result = [];\nfor (const x of nums2) {\n    for (let j = 0; j < nums1.length; j++) {\n        if (!used[j] && nums1[j] === x) {\n            result.push(x);\n            used[j] = true;\n            break;\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8},"statementBundles":{"8":{"startLine":8,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const used = Array(nums1.length).fill(false);\nconst result: Array<number> = [];\nfor (const x of nums2) {\n    for (let j = 0; j < nums1.length; j++) {\n        if (!used[j] && nums1[j] === x) {\n            result.push(x);\n            used[j] = true;\n            break;\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8},"statementBundles":{"8":{"startLine":8,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Boolean> used = new ArrayList<>();\nfor (int index = 0; index < nums1.size(); index++) {\n    used.add(false);\n}\nList<Integer> result = new ArrayList<>();\nfor (Integer x : nums2) {\n    for (int j = 0; j < nums1.size(); j++) {\n        if ((!used.get(j) && nums1.get(j) == x)) {\n            result.add(x);\n            used.set(j, true);\n            break;\n        }\n    }\n}","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":9,"7":10,"8":11},"statementBundles":{"1":{"startLine":1,"endLine":4},"8":{"startLine":11,"endLine":14}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<bool> used = Enumerable.Repeat<bool>(false, nums1.Count).ToList();\nList<int> result = new();\nforeach (int x in nums2) {\n    for (int j = 0; j < nums1.Count; j++) {\n        if (!used[j] && nums1[j] == x) {\n            result.Add(x);\n            used[j] = true;\n            break;\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8},"statementBundles":{"8":{"startLine":8,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<bool> used = vector<bool>(nums1.size(), false);\nvector<int> result;\nfor (int x : nums2) {\n    for (int j = 0; j < nums1.size(); j++) {\n        if ((!used[j] && nums1[j] == x)) {\n            result.push_back(x);\n            used[j] = true;\n            break;\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8},"statementBundles":{"8":{"startLine":8,"endLine":11}}}}}},{"id":"repeated-work-probe","kind":"case-probe","title":"Five values looked at 14 positions. With 1,000 numbers in each list, about how many could this method look at?","workspacePanel":"trace","options":[{"id":"about-thousand","label":"About 1,000","rationale":"That is what a single value of nums2 can cost. The 3 alone looked at every position of nums1.","isCorrect":false},{"id":"about-two-thousand","label":"About 2,000","rationale":"That would be one pass over each list. Here every value of nums2 starts its own pass over nums1.","isCorrect":false},{"id":"about-million","label":"About 1,000,000","rationale":"Each of the 1,000 values in nums2 can look at all 1,000 positions of nums1, the way the 3 and the third 2 did.","isCorrect":true}]},{"id":"state-meaning","kind":"case-probe","title":"The third 2 is about to walk nums1 again. Which fact would let it skip the walk?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-third-two","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"used":[1,2]},{"name":"nums2","values":[2,3,2,2,1],"i":3,"labels":{"i":"x"}},{"name":"result","values":[2,2]}]}}]},"options":[{"id":"unused-count","label":"How many unused 2s nums1 still has","rationale":"All the walk decides is whether an unused 2 is left. A count answers that in one lookup, and here it would read 0.","isCorrect":true},{"id":"contains-value","label":"Whether nums1 contains a 2 at all","rationale":"nums1 does contain 2s, and both are already used. A yes or no cannot tell this 2 from the first one.","isCorrect":false},{"id":"first-position","label":"Where the first 2 sits in nums1","rationale":"The first 2 sits at position 1, and the very first value of nums2 used it. Its position says nothing about the copies after it.","isCorrect":false}]},{"id":"dry-run-setup","kind":"info","title":"A count for every value, starting from nums1","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"count-first-one","title":"The first 1 gets an entry","summary":"1 has not been counted yet, so its entry starts at 1.","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"current":0}],"seen":{"1":1},"seenHighlight":1,"labels":{"seen":"counts"}}},{"id":"count-first-two","title":"The first 2 gets its own entry","summary":"Each value keeps a separate count.","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"current":1}],"seen":{"1":1,"2":1},"seenHighlight":2,"labels":{"seen":"counts"}}},{"id":"count-second-two","title":"The second 2 adds to the entry that is there","summary":"The entry for 2 goes from 1 to 2. Setting it back to 1 would lose a copy.","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"current":2}],"seen":{"1":1,"2":2},"seenHighlight":2,"labels":{"seen":"counts"}}},{"id":"count-second-one","title":"The second 1 does the same","summary":"After one pass, counts says nums1 has two 1s and two 2s, all unused.","state":{"arrays":[{"name":"nums1","values":[1,2,2,1],"current":3}],"seen":{"1":2,"2":2},"seenHighlight":1,"labels":{"seen":"counts"}}}]},"body":["Keep a number like that for every value at once, in a map. A map pairs each key with an entry. Here each value is a key, and its entry is how many of its copies in nums1 are still unused. Call the map counts.","Before any value of nums2 is looked at, counts starts as a tally of nums1: how many copies of each value it has."]},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Scan nums2 against counts","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"scan-0","state":{"arrays":[{"name":"nums2","values":[2,3,2,2,1],"i":0,"labels":{"i":"x"}},{"name":"result","values":[]}],"seen":{"1":2,"2":2},"labels":{"seen":"counts"},"seenHighlight":2}},{"id":"scan-1","state":{"arrays":[{"name":"nums2","values":[2,3,2,2,1],"i":1,"labels":{"i":"x"}},{"name":"result","values":[2]}],"seen":{"1":2,"2":1},"labels":{"seen":"counts"},"seenHighlight":3}},{"id":"scan-2","state":{"arrays":[{"name":"nums2","values":[2,3,2,2,1],"i":2,"labels":{"i":"x"}},{"name":"result","values":[2]}],"seen":{"1":2,"2":1},"labels":{"seen":"counts"},"seenHighlight":2}},{"id":"scan-3","state":{"arrays":[{"name":"nums2","values":[2,3,2,2,1],"i":3,"labels":{"i":"x"}},{"name":"result","values":[2,2]}],"seen":{"1":2,"2":0},"labels":{"seen":"counts"},"seenHighlight":2}},{"id":"scan-4","state":{"arrays":[{"name":"nums2","values":[2,3,2,2,1],"i":4,"labels":{"i":"x"}},{"name":"result","values":[2,2]}],"seen":{"1":2,"2":0},"labels":{"seen":"counts"},"seenHighlight":1}},{"id":"scan-5","state":{"arrays":[{"name":"nums2","values":[2,3,2,2,1]},{"name":"result","values":[2,2,1]}],"seen":{"1":1,"2":0},"labels":{"seen":"counts"}}}]},"beats":[{"id":"first-two","title":"The scan of nums2 starts with a 2, and counts shows two unused 2s. What happens to this 2?","options":[{"id":"keep-no-lower","label":"It goes into result, and the count for 2 stays at 2","rationale":"Then counts would still show two unused 2s after one was taken, and all three 2s of nums2 would get in.","isCorrect":false},{"id":"keep-and-lower","label":"It goes into result, and the count for 2 drops to 1","rationale":"One of nums1's two 2s is now used, so one is left for a later 2.","isCorrect":true},{"id":"wait-for-total","label":"It waits until the scan knows how many 2s nums2 has","rationale":"Nothing about later values is needed. A count above zero already says nums1 has a partner for this 2.","isCorrect":false}]},{"id":"no-entry","title":"The next value is 3, and counts has no entry for it. What happens?","options":[{"id":"stop-scan","label":"The scan stops, because counts cannot answer for 3","rationale":"A value nums1 lacks is ordinary input, and the values after it still need their turn.","isCorrect":false},{"id":"skip-three","label":"It is skipped, and counts stays as it is","rationale":"No entry means nums1 never had a 3, which is the same as zero unused copies.","isCorrect":true},{"id":"add-entry","label":"It goes into result and gets a new entry in counts","rationale":"Entries come only from nums1. A new one here would count a 3 that nums1 never had.","isCorrect":false}]},{"id":"last-copy","title":"This 2 finds a count of 1. Is one unused copy enough?","options":[{"id":"keep-to-zero","label":"Yes: it goes into result and the count drops to 0","rationale":"A count of 1 means exactly one 2 in nums1 is still unused, and this 2 takes it.","isCorrect":true},{"id":"hold-reserve","label":"No: the last copy has to stay in counts","rationale":"Nothing is held back. Skipping here would leave result with one 2 when each list has at least two.","isCorrect":false},{"id":"floor-at-one","label":"Yes: it goes into result and the count stays at 1","rationale":"The count has to reach 0, because that is how counts shows nums1 has run out of 2s.","isCorrect":false}]},{"id":"spent","title":"The third 2 arrives. counts still has an entry for 2, and it reads 0. Is this 2 kept?","options":[{"id":"entry-exists","label":"Yes: 2 has an entry, so nums1 contains it","rationale":"nums1 does contain 2s, but both are used. An entry that reads 0 has nothing left to give.","isCorrect":false},{"id":"go-negative","label":"Yes, and the count drops to -1","rationale":"A count below zero would mean nums1 gave away a 2 it never had, and result would hold three 2s.","isCorrect":false},{"id":"skip-spent","label":"No: a count of 0 means both of nums1's 2s are used","rationale":"The check is on the number in the entry. Only a count above zero keeps a value.","isCorrect":true}]},{"id":"returns","title":"One value is left, a 1. What does the function return after the scan?","options":[{"id":"two-two-one-one","label":"[2, 2, 1, 1]","rationale":"counts ends with one unused 1, but nums2 has no second 1 to pair with it. Unused counts are never added.","isCorrect":false},{"id":"two-two-one","label":"[2, 2, 1]","rationale":"The 1 finds a count of 2, so it goes into result. The scan is over, and result is returned as it stands.","isCorrect":true},{"id":"two-two","label":"[2, 2]","rationale":"counts shows two unused 1s when this 1 arrives, so it is kept like any other match.","isCorrect":false}]}]},{"id":"edge-case-intro","kind":"info","title":"The scan returned [2, 2, 1]. Next, two other pairs of lists.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"scan-finished","state":{"arrays":[{"name":"nums2","values":[2,3,2,2,1]},{"name":"result","values":[2,2,1]}],"seen":{"1":1,"2":0},"labels":{"seen":"counts"}}}]},"body":["In the first pair, the two lists have no value in common. In the second, both lists hold several 0s.","Does the same tally and scan give the right answer on each?"]},{"id":"absent-value-probe","kind":"case-probe","title":"In the first pair, the lists share no value. What does the function return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"nothing-shared","state":{"arrays":[{"name":"nums1","values":[1,3,5]},{"name":"nums2","values":[2,4,6]}],"seen":{"1":1,"3":1,"5":1},"labels":{"seen":"counts"}}}]},"options":[{"id":"empty-list","label":"An empty list, because nothing was kept","rationale":"No value of nums2 has an entry in counts, so each one is skipped. result was created empty before the scan, so it comes back empty with no extra case.","isCorrect":true},{"id":"minus-one","label":"-1, because nothing matched","rationale":"The return value is always a list. With no matches it is a list with nothing in it.","isCorrect":false},{"id":"unused-values","label":"The values of nums1, because none were used","rationale":"Unused counts stay in counts. Only values read from nums2 ever go into result.","isCorrect":false}]},{"id":"zero-value-probe","kind":"case-probe","title":"In the second pair, x is 0, and its entry in counts reads 2. Is this 0 kept?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-lookup","state":{"arrays":[{"name":"nums1","values":[0,0,1]},{"name":"nums2","values":[0,0,0],"i":0,"labels":{"i":"x"}}],"seen":{"0":2,"1":1},"seenHighlight":0,"labels":{"seen":"counts"}}}]},"options":[{"id":"zero-means-empty","label":"No: 0 means nothing is left","rationale":"That reads the value as if it were a count. The value is 0, and the number of unused copies is 2.","isCorrect":false},{"id":"zero-not-key","label":"No: 0 cannot be a key in counts","rationale":"Any number can be a key. counts already holds an entry for 0.","isCorrect":false},{"id":"count-decides","label":"Yes: the entry shows two unused 0s","rationale":"The key is the value and the entry is its count. Only the count decides, and it is 2. The next 0 is kept too, the third finds a count of 0, and the function returns [0, 0].","isCorrect":true}]},{"id":"ready-to-code","kind":"info","title":"The tally and the scan handle every case, so the function is next.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-any-code","state":{"arrays":[{"name":"nums1","values":[1,2,2,1]},{"name":"nums2","values":[2,3,2,2,1]},{"name":"result","values":[]}],"seen":{},"labels":{"seen":"counts"}}}]},"body":["The function first reads the first list once and counts how many copies of each value it has.","It starts an empty result, then reads the second list one value at a time. If that value's count is above zero, the value goes into the result and its count goes down by one. A value with no count, or a count of zero, is skipped.","After the last value, the function returns the result."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Write the tally and the scan","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"Count one list, then spend those counts on the other","workspacePanel":"code","takeaways":[{"title":"An entry is a number of unused copies","body":"counts maps each value to how many of its copies in nums1 are still unused. A yes or no per value could not have stopped the third 2 of nums2."},{"title":"Keeping a value costs one copy","body":"Each value that goes into the result lowers its count by one, so a value is kept at most as many times as nums1 has it. nums2 sets the other limit by how many times it offers the value."},{"title":"No entry and a count of 0 mean the same thing","body":"Either way nums1 has nothing left to pair, so the value is skipped. That one check also covers two lists with nothing in common."},{"title":"Time O(m + n), space O(k)","body":"Each list is read once. Each value costs a map lookup and at most one update, both constant time on average, so the time is O(m + n) for lists of m and n numbers. Walking nums1 for every value looked at up to m × n positions. Apart from the result, the only extra space is the map: one entry for each of the k distinct values in nums1."}]}],"slidesOrigin":"authored"}}
