{"id":"intersection-of-two-arrays","title":"Intersection of Two Arrays","difficulty":"easy","patterns":["hash-map"],"primaryConcept":"hash-map-complements","concepts":["hash-map-complements"],"problemForm":"intro","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 unique intersection values. The result can be returned in any order.","examples":[{"input":"nums1 = [1,2,2,1], nums2 = [2,2]","output":"[2]","explanation":"Only value 2 appears in both arrays, and it appears once in the output."},{"input":"nums1 = [4,9,5], nums2 = [9,4,9,8,4]","output":"[9,4]","explanation":"Values 4 and 9 appear in both arrays. Output order does not matter."}],"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-must-be-unique","text":"Each value in the result must be unique"},{"id":"the-result-can-be-returned-in-any-order","text":"The result can be returned in any order"}],"starterCode":"class Solution:\n    def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        # Your code here\n        pass","functionName":"intersection","testCases":[{"id":"1","input":{"nums1":[1,2,2,1],"nums2":[2,2]},"expected":[2],"description":"Duplicates collapse to one output value."},{"id":"2","input":{"nums1":[4,9,5],"nums2":[9,4,9,8,4]},"expected":[9,4],"description":"Two shared values in different orders."},{"id":"3","input":{"nums1":[1,3,5],"nums2":[2,4,6]},"expected":[],"description":"No shared values."},{"id":"4","input":{"nums1":[7],"nums2":[7,7,7]},"expected":[7],"description":"Single shared value with duplicates."},{"id":"5","input":{"nums1":[10,20,30,40],"nums2":[5,10,15,20]},"expected":[10,20],"description":"Two shared values among distinct arrays."},{"id":"h1","input":{"nums1":[0,1,2],"nums2":[0]},"expected":[0],"description":"Zero can be part of the intersection."},{"id":"h2","input":{"nums1":[1000,999,998,997],"nums2":[997,997,1000]},"expected":[997,1000],"description":"Large values with duplicate hits."},{"id":"h3","input":{"nums1":[1,2,3],"nums2":[4,5,6]},"expected":[],"description":"Disjoint arrays return an empty list."},{"id":"h4","input":{"nums1":[0,2,2,4,6],"nums2":[6,6,0,8]},"description":"Zero and a larger value both survive deduplication.","expected":[0,6]},{"id":"h5","input":{"nums1":[0,1,2,3],"nums2":[4,3,0,0]},"description":"Zero repeated in nums2 appears once in the result.","expected":[0,3]}],"hints":[{"level":1,"content":"The output should contain each shared value at most once.","revealPattern":false},{"level":2,"content":"Put one array into a set, then scan the other array for membership.","revealPattern":true},{"level":3,"content":"Use a set for the result too, so repeated hits do not duplicate the output.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Pick the approach whose membership test does not rescan an array each time.","approaches":[{"id":"nested-scan","name":"Compare every pair","summary":"For each value in nums1, scan all of nums2 for a match, then strip duplicates.","decisionReason":"Every nums1 value re-walks all of nums2, so the same membership question is paid for again and again.","complexity":{"time":"O(m*n)","space":"O(k)"},"tradeoffs":["Little extra state, but each membership test rescans the whole second array."],"isOptimal":false},{"id":"set-membership","name":"Source set, result set","summary":"Store nums1 as a set, scan nums2 once, and collect matches in a result set.","decisionReason":"One probe per nums2 value replaces the rescan, and a result set drops repeats for free.","complexity":{"time":"O(m + n)","space":"O(m + k)"},"tradeoffs":["Spends O(m) space on the set to make every membership test a single probe."],"isOptimal":true}]},"codingCheckpoints":[{"id":"build-membership-set","title":"Build the source set","description":"Store the values of `nums1` as a set so each lookup is one probe.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"initializes_set_state","scope":"first-input-seeded-set","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Keeping `nums1` as a list and rescanning it for every `nums2` value","Rebuilding the set inside the loop instead of once before it"],"hint":"One set holds every value of the first array, built once before the scan.","semanticSpec":{"intent":"Initialize set-membership state from the first array.","doneWhen":"The first array is represented by a reusable set before the scan.","shouldFailWhen":"This step should fail if no reusable set membership state is initialized.","roles":["first array","source set"],"mustProve":["The solution initializes set membership state from the first array."],"mustNotAccept":["A repeated linear scan over the first array."],"proofSnippets":[{"id":"py-intersection-build-membership-set","language":"python","code":"class Solution:\n    def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        values = set(nums1)"}]}},{"id":"scan-second-array","title":"Scan the second array","description":"Visit each value of `nums2` as a candidate shared value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-second-input","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Checking only the first value of `nums2`","Looping over the source set instead of `nums2`"],"hint":"Any value in the second array could be part of the intersection.","semanticSpec":{"intent":"Scan candidate values from the second input array.","doneWhen":"The solution loops over the second array.","shouldFailWhen":"This step should fail if the second input sequence is not scanned.","roles":["second array","current value"],"mustProve":["The traversal reads the second input sequence."],"mustNotAccept":["A fixed check against one position."],"proofSnippets":[{"id":"py-intersection-scan-second-array","language":"python","code":"class Solution:\n    def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        values = set(nums1)\n        for num in nums2:\n            pass"}]}},{"id":"check-membership","title":"Test membership in the source set","description":"For each value of `nums2`, ask the source set whether it holds that value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"checks_set_membership","scope":"membership-check-first-input-set","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Probing the result set instead of the source set","Recording every value without testing membership first"],"hint":"Only values the source set already holds belong in the output.","semanticSpec":{"intent":"Use set membership to test for a shared value.","doneWhen":"The current candidate is tested against the source set.","shouldFailWhen":"This step should fail if no set membership guard exists.","roles":["current value","source set"],"mustProve":["The solution performs a set membership check."],"mustNotAccept":["Unconditionally adding candidates to the result."],"proofSnippets":[{"id":"py-intersection-check-membership","language":"python","code":"class Solution:\n    def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        values = set(nums1)\n        for num in nums2:\n            if num in values:\n                pass"}]}},{"id":"record-match","title":"Record matches in a result set","description":"When a value passes the membership test, add it to a result set.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"adds_member_to_set","scope":"add-edge","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Collecting matches in a list, which lets a repeat appear twice","Recording a value that did not pass the membership test"],"hint":"A result set absorbs a repeated match without duplicating it.","semanticSpec":{"intent":"Write matching values into a result set.","doneWhen":"Values that pass membership are inserted into a set-like result.","shouldFailWhen":"This step should fail if matches are not recorded in set state.","roles":["current value","result set"],"mustProve":["The solution writes matching values into set state."],"mustNotAccept":["A list append that can return duplicates."],"proofSnippets":[{"id":"py-intersection-record-match","language":"python","code":"class Solution:\n    def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        values = set(nums1)\n        result = set()\n\n        for num in nums2:\n            if num in values:\n                result.add(num)"}]}},{"id":"return-result","title":"Return the result values","description":"Project the result set into the returned array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"returns_projected_set_result","scope":"project-result","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Returning the source set built from the first array","Returning a boolean instead of the matching values"],"hint":"The answer is the result set projected to an array, in any order.","semanticSpec":{"intent":"Project the result set into the returned value.","doneWhen":"The function returns a sequence derived from the result set.","shouldFailWhen":"This step should fail if the result set is not projected or returned.","roles":["result set","return value"],"mustProve":["The solution projects the result set into the return value."],"mustNotAccept":["Returning the first array's source set."],"proofSnippets":[{"id":"py-intersection-return-result","language":"python","code":"class Solution:\n    def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:\n        values = set(nums1)\n        result = set()\n\n        for num in nums2:\n            if num in values:\n                result.add(num)\n\n        return list(result)"}]}}],"slides":[{"id":"the-task","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Which values live in both arrays?","workspacePanel":"problem","body":["You get two arrays and must return the values that appear in both, each value listed once, in any order.","The obvious way is to take each value of nums2 and search nums1 for it. Watch it work, and watch what it repeats."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Check every pair","summary":"Scanning all of nums1 for each value of nums2 finds every shared value, but it gets there by reading the same array over and over. Watch how much of nums1 each value re-reads.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\nfor b in nums2:\n    for a in nums1:\n        if a == b and b not in result:\n            result.append(b)","steps":[{"id":"first-value-walks","title":"9 walks all of nums1","codeLine":4,"summary":"b is 9, the first value of nums2. It compares against 4, 9, 5: a full pass over nums1 to find the one match.","state":{"arrays":[{"name":"nums1","values":[4,9,5],"i":1,"labels":{"i":"a"}},{"name":"nums2","values":[9,4,9,8,4],"i":0,"labels":{"i":"b"}}],"labels":{}}},{"id":"second-value-rewalks","title":"4 walks all of nums1 again","codeLine":3,"summary":"b moves to 4 and the inner scan restarts from the front: the same three values of nums1 are read a second time.","state":{"arrays":[{"name":"nums1","values":[4,9,5],"i":0,"labels":{"i":"a"}},{"name":"nums2","values":[9,4,9,8,4],"i":1,"labels":{"i":"b"}}],"labels":{}}},{"id":"third-value-rewalks","title":"8 walks all of nums1 too","codeLine":3,"summary":"8 matches nothing, but only after another full pass over nums1. Five values of nums2, five full rescans of nums1.","state":{"arrays":[{"name":"nums1","values":[4,9,5],"i":2,"labels":{"i":"a"}},{"name":"nums2","values":[9,4,9,8,4],"i":3,"labels":{"i":"b"}}],"labels":{}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nfor (const b of nums2) {\n    for (const a of nums1) {\n        if (a === b && !result.includes(b)) {\n            result.push(b);\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<number> = [];\nfor (const b of nums2) {\n    for (const a of nums1) {\n        if (a === b && !result.includes(b)) {\n            result.push(b);\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> result = new ArrayList<>();\nfor (Integer b : nums2) {\n    for (Integer a : nums1) {\n        if ((a == b && !result.contains(b))) {\n            result.add(b);\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> result = new();\nforeach (int b in nums2) {\n    foreach (int a in nums1) {\n        if (a == b && !result.Contains(b)) {\n            result.Add(b);\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> result;\nfor (int b : nums2) {\n    for (int a : nums1) {\n        if ((a == b && !containsValue(result, b))) {\n            result.push_back(b);\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5},"statementBundles":{"5":{"startLine":5,"endLine":8}}}}},"body":["For each value of nums2, scan all of nums1 for a match."]},{"id":"waste-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the waste","title":"How many comparisons does this scan cost?","summary":"Each of the 5 values of nums2 walked all 3 values of nums1 before moving on.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"waste-cost-state","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4]}],"comparisons":"5 x 3 = 15"}}]},"options":[{"id":"m-times-n","label":"Up to 5 times 3, about 15: every nums2 value re-walks all of nums1, so m times n in general","rationale":"Nothing remembers what nums1 contains, so each of the 5 nums2 values rediscovers all 3 nums1 values, giving up to m times n comparisons.","isCorrect":true},{"id":"m-plus-n","label":"About 5 plus 3, since each array is read once","rationale":"nums1 is not read once. It is re-walked from the front for every value of nums2, so the cost multiplies rather than adds.","isCorrect":false},{"id":"just-five","label":"About 5, one comparison per value of nums2","rationale":"One value of nums2 takes a whole pass over nums1, so 5 values cost 5 full passes.","isCorrect":false}],"answer":"Up to 5 times 3, around 15 comparisons here, and m times n in general. Each nums2 value re-walks all of nums1. A way to ask \"is this value in nums1?\" without walking is the missing piece."},{"id":"membership-state-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Pick the state","title":"What makes \"is this value in nums1?\" one probe?","summary":"The brute force re-walks nums1 for every value of nums2.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"membership-probe-state","state":{"arrays":[{"name":"nums2","values":[9,4,9,8,4],"i":0,"labels":{"i":"num"}}],"seenSet":[4,5,9],"seenHighlight":9,"labels":{"seen":"values"}}}]},"options":[{"id":"set-of-one-array","label":"Hold nums1 as a set of its values","rationale":"A set answers \"do you contain this value?\" in one probe, so scanning nums2 never re-walks nums1.","isCorrect":true},{"id":"sort-both","label":"Sort both arrays first","rationale":"Sorting costs O(n log n) and still walks both arrays; a set answers membership directly without ordering.","isCorrect":false},{"id":"count-values","label":"Count how many times each value appears","rationale":"Counts answer \"how many\" but the question is only \"present or not\"; the extra tally is state the answer never reads.","isCorrect":false}],"answer":"Store nums1 as a set of its values. Each value of nums2 then asks one membership question and gets one answer."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4]}],"seenSet":[4,5,9],"labels":{"seen":"values"}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"One source set, one result set","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4],"i":0,"labels":{"i":"num"}}],"seenSet":[4,5,9],"labels":{"seen":"values"}}}]},"body":["values holds nums1 as a set: {4, 5, 9}. The scan walks nums2 = [9, 4, 9, 8, 4] from the left, and 9 turns up twice.","A match has to be saved somewhere the output can be read from later. Watch where each hit lands, and what the repeated 9 does once it gets there."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the scan","title":"Trace the membership scan","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-hit","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4],"i":0,"labels":{"i":"num"}}],"seenSet":[4,5,9],"seenHighlight":9,"labels":{"seen":"values"}}},{"id":"record-into-result","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4],"i":1,"labels":{"i":"num"}}],"seenSet":[9],"labels":{"seen":"result"}}},{"id":"repeat-hit","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4],"i":2,"labels":{"i":"num"}}],"seenSet":[9,4],"seenHighlight":9,"labels":{"seen":"result"}}}]},"beats":[{"id":"first-hit","title":"Where does the matched 9 get recorded?","summary":"num is 9, values holds {4, 5, 9}, so the probe hits.","prompt":"The probe on 9 hits. The match needs to land somewhere the output is read from.","options":[{"id":"into-result-set","label":"Into a separate result set, which becomes {9}","rationale":"Keeping matches apart from values means later repeats cannot duplicate the output, and values stays a clean membership table.","isCorrect":true},{"id":"into-values","label":"Back into values, which becomes {4, 5, 9} unchanged","rationale":"values is the source set the probes read from. Writing matches there blurs what it means and adds nothing the output can use.","isCorrect":false},{"id":"nowhere","label":"Nowhere, a running count of hits is enough","rationale":"A count cannot say which values matched, and the output is the values themselves, not how many.","isCorrect":false}],"answer":"The match lands in a separate result set, now {9}, kept apart from the source set values."},{"id":"record-into-result","title":"The scan reaches 4, also a hit, so what does result hold?","summary":"result is {9}, num is now 4, and values holds it too.","prompt":"The probe on 4 hits, and result already holds 9.","options":[{"id":"grows-to-both","label":"result grows to {9, 4}: each fresh match is added","rationale":"Every value that passes the probe is added, so a second distinct match joins the ones already collected.","isCorrect":true},{"id":"replaces-nine","label":"result becomes {4}, the latest match replacing 9","rationale":"Adding to a set keeps the earlier members. Nothing overwrites 9 when 4 is recorded.","isCorrect":false},{"id":"stays-one","label":"result stays {9}, since one match per array is enough","rationale":"Every shared value belongs in the output.","isCorrect":false}],"answer":"result grows to {9, 4}: 4 is a fresh match, so it joins 9."},{"id":"repeat-hit","title":"nums2 hits 9 a second time, so what changes?","summary":"result holds {9, 4}, and num is the second 9 in nums2.","prompt":"This value of nums2 is another 9.","options":[{"id":"no-duplicate","label":"Nothing: result already holds 9, and a set ignores the repeat","rationale":"A set keeps each value once, so the second 9 leaves result as {9, 4}.","isCorrect":true},{"id":"second-copy","label":"A second 9 joins result, making {9, 4, 9}","rationale":"That would duplicate the output. A set is exactly what prevents the second copy.","isCorrect":false},{"id":"removes-nine","label":"The 9 is removed because it was seen twice","rationale":"Membership records presence; it never toggles a value out on a repeat.","isCorrect":false}],"answer":"The repeat changes nothing: result stays {9, 4}. Projected to a list, the answer is [9, 4] in any order."}]},{"id":"list-result-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"What breaks if the scan probes its own array?","summary":"One reflex is to let the set and the scan come from the same array, since the code still has a set, a loop, and a membership check. It can still record the obvious hits like 9 and 4. Watch the value that should not survive.","workspacePanel":"trace","pitfall":"The code below builds the source set from nums2, then scans nums2 against it.","whyItMatters":"Probe the array you are not scanning. When the set and the scan come from the same array, every value finds itself present, so values that live in only one array leak in: 8 is in nums2 but never in nums1, yet it survives. Building the set from nums2 is fine, but only if you then scan nums1 against it.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"values = set(nums2)\nresult = set()\nfor num in nums2:\n    if num in values:\n        result.add(num)\nreturn list(result)","steps":[{"id":"wrong-source-set","title":"The set is built from nums2","codeLine":1,"summary":"values is set(nums2) = {4, 8, 9}. It now holds 8, a value that lives only in nums2 and never in nums1.","state":{"seenSet":[4,8,9],"seenHighlight":8,"labels":{"seen":"values"}}},{"id":"nine-recorded","title":"9 tests present and is recorded","codeLine":5,"summary":"nums2 starts on 9, values holds it, so 9 goes into result. result is {9}, matching the expected output so far.","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4],"i":0,"labels":{"i":"num"}}],"seenSet":[9],"labels":{"seen":"result"}}},{"id":"eight-leaks","title":"8 tests present too","codeLine":5,"summary":"The scan reaches 8. Because values was built from nums2, 8 is in it, so 8 is recorded. result is {9, 4, 8}.","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4],"i":3,"labels":{"i":"num"}}],"seenSet":[9,4,8],"seenHighlight":8,"labels":{"seen":"result"}}},{"id":"leak-returned","title":"8 comes back in the answer","codeLine":6,"summary":"It returns {9, 4, 8}. But 8 never appears in nums1, so it is not a shared value. The wrong source set leaked it.","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4]}],"seenSet":[9,4,8],"seenHighlight":8,"labels":{"seen":"result"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const values = new Set(nums2);\nconst result = new Set();\nfor (const num of nums2) {\n    if (values.has(num)) {\n        result.add(num);\n    }\n}\nreturn Array.from(result);","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 values = new Set(nums2);\nconst result: Set<number> = new Set();\nfor (const num of nums2) {\n    if (values.has(num)) {\n        result.add(num);\n    }\n}\nreturn Array.from(result);","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":"Set<Integer> values = new HashSet<Integer>(nums2);\nSet<Integer> result = new HashSet<Integer>();\nfor (Integer num : nums2) {\n    if (values.contains(num)) {\n        result.add(num);\n    }\n}\nreturn new ArrayList<Integer>(result);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"HashSet<int> values = new(nums2);\nHashSet<int> result = new();\nforeach (int num in nums2) {\n    if (values.Contains(num)) {\n        result.Add(num);\n    }\n}\nreturn result.ToList();","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":"unordered_set<int> values = unordered_set<int>(nums2.begin(), nums2.end());\nunordered_set<int> result;\nfor (int num : nums2) {\n    if (values.count(num)) {\n        result.insert(num);\n    }\n}\nreturn vector<int>(result.begin(), result.end());","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8},"statementBundles":{"5":{"startLine":5,"endLine":7}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"arrays":[{"name":"nums1","values":[1,3,5]},{"name":"nums2","values":[2,4,6],"i":0,"labels":{"i":"num"}}],"seenSet":[1,3,5],"labels":{"seen":"values"}}}]},"body":["The scan recorded matches when the arrays overlapped. The membership test is easiest to question on the input where nothing ever matches.","Worth checking before coding is a pair of arrays that share no value at all, and where a shared value happens to be 0."]},{"id":"no-overlap-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What comes back when nothing is shared?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-overlap-state","state":{"arrays":[{"name":"nums1","values":[1,3,5]},{"name":"nums2","values":[2,4,6],"i":2,"labels":{"i":"num"}}],"seenSet":[1,3,5],"labels":{"seen":"values"}}}]},"summary":"nums1 = [1, 3, 5], nums2 = [2, 4, 6], and the scan is on the last value.","options":[{"id":"empty-list","label":"An empty list: every probe missed, so result never grew","rationale":"No value of nums2 is in values, so result stays empty and projects to [].","isCorrect":true},{"id":"all-of-nums2","label":"All of nums2, since the scan visited every value","rationale":"Visiting a value is not the same as matching it. Only values present in the source set are recorded.","isCorrect":false},{"id":"needs-guard","label":"It errors unless a special empty-input guard is added","rationale":"An all-miss scan simply records nothing; an empty result set projects to an empty list with no extra branch.","isCorrect":false}],"answer":"An empty list. Disjoint arrays make every probe miss, so the result set is never written and projects to []."},{"id":"zero-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Rule out a special case","title":"Is 0 treated like any other shared value?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-state","state":{"arrays":[{"name":"nums1","values":[0,2,4]},{"name":"nums2","values":[6,0,8],"i":1,"labels":{"i":"num"}}],"seenSet":[0,2,4],"seenHighlight":0,"labels":{"seen":"values"}}}]},"summary":"nums1 = [0, 2, 4], nums2 = [6, 0, 8], and the scan reaches the 0.","options":[{"id":"zero-matches","label":"Yes: 0 is in values, so it is recorded like any match","rationale":"A set stores 0 as an ordinary value, and the membership probe on 0 hits.","isCorrect":true},{"id":"zero-falsy","label":"No: 0 is skipped because the probe treats it as nothing","rationale":"Membership tests presence of the value, not its truthiness. 0 is a value the set holds.","isCorrect":false},{"id":"zero-needs-branch","label":"No: 0 needs its own branch to be recorded","rationale":"The set treats 0 like 4 or 9; no separate branch is needed for it.","isCorrect":false}],"answer":"0 is recorded like any other shared value: the source set holds it, and the probe on the 0 in nums2 hits."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"A few short steps, and the result set is what keeps the output unique.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"arrays":[{"name":"nums1","values":[4,9,5]},{"name":"nums2","values":[9,4,9,8,4]}],"seenSet":[4,5,9],"labels":{"seen":"values"}}}]},"body":["Store one array as a set, scan the other once, probe membership on each value, collect the hits in a result set, and return that set as a list."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the source-set scan","summary":"Now build it: store nums1 as a set, scan each value of nums2, probe the set for it, add the ones that hit to a result set, then return that set as a list.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"Store one array as a set for fast membership, and collect matches in a result set so repeats never duplicate the output.","body":["The brute force re-walked one array for every value of the other. A set turns that walk into a single membership probe, taking the work from O(m*n) to O(m + n).","The output is unique by construction: a result set absorbs a value matched twice, so no dedup pass is needed."],"takeaways":[{"title":"A set answers membership in one probe","body":"Storing nums1 as a set replaces the rescan of it with a single lookup per value of nums2."},{"title":"The result set does the deduplication","body":"A value matched twice is added twice, but a set keeps it once, so the output stays unique with no extra work."},{"title":"Order is free","body":"The contract accepts any order, so the result set projects straight to a list without sorting."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
