{"id":"contains-duplicate","title":"Contains Duplicate","difficulty":"easy","patterns":["hash-map"],"primaryConcept":"hash-map-complements","concepts":["hash-map-complements"],"problemForm":"intro","companies":["Amazon","Google","Microsoft","Apple"],"category":"hash-tables","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length","valueRange":{"min":-100,"max":100},"sizes":[8,16,32,64]},"description":"Given an integer array `nums`, return `True` if any value appears at least twice in the array. Return `False` if every value is distinct.","examples":[{"input":"nums = [1,2,3,1]","output":"true","explanation":"The value 1 appears twice."},{"input":"nums = [1,2,3,4]","output":"false","explanation":"Every value appears once."},{"input":"nums = [1,1,1,3,3,4,3,2,4,2]","output":"true","explanation":"Several values repeat."}],"constraints":[{"id":"1-len-nums-10-5","text":"1 <= len(nums) <= 10^5","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":100000}},{"id":"10-9-nums-i-10-9","text":"-10^9 <= nums[i] <= 10^9","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-1000000000,"max":1000000000}}],"starterCode":"class Solution:\n    def containsDuplicate(self, nums: list[int]) -> bool:\n        # Your code here\n        pass","functionName":"containsDuplicate","testCases":[{"id":"1","input":{"nums":[1,2,3,1]},"expected":true,"description":"Duplicate appears after distinct values."},{"id":"2","input":{"nums":[1,2,3,4]},"expected":false,"description":"All values are distinct."},{"id":"3","input":{"nums":[1,1,1,3,3,4,3,2,4,2]},"expected":true,"description":"Many repeated values."},{"id":"4","input":{"nums":[0]},"expected":false,"description":"Single value cannot duplicate."},{"id":"5","input":{"nums":[-1,-2,-3,-1]},"expected":true,"description":"Negative duplicate."},{"id":"h1","input":{"nums":[1000000000,-1000000000,0]},"expected":false,"description":"Large distinct values."},{"id":"h2","input":{"nums":[5,4,3,2,1,5]},"expected":true,"description":"Duplicate at the end."},{"id":"h3","input":{"nums":[7,7]},"expected":true,"description":"Smallest duplicate case."},{"id":"h4","input":{"nums":[1,2,3,4,5]},"expected":false,"description":"A longer distinct prefix still has no duplicate."},{"id":"h5","input":{"nums":[2,3,4,5,2]},"expected":true,"description":"Duplicate appears only after the full scan."}],"hints":[{"level":1,"content":"You only need to know whether a value has appeared before.","revealPattern":false},{"level":2,"content":"Keep a set of values already seen during the scan.","revealPattern":true},{"level":3,"content":"If the current value is already in the set, return immediately.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which way of finding a repeat should the code use?","decisionPrompt":"Compare how much work each one does on a list with no repeat.","approaches":[{"id":"nested-scan","name":"Look back from each number","summary":"At each number, compare it with every number before it.","decisionReason":"A list of n numbers with no repeat takes n(n-1)/2 comparisons, which is about 5 billion at the 100,000-number limit.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["It needs no extra memory, but the comparisons grow with the square of the list length."],"isOptimal":false},{"id":"seen-set","name":"One pass with a set","summary":"Look each number up in a set of the earlier numbers, then add it.","decisionReason":"Each of the n numbers costs one lookup and at most one add, so the scan is O(n) on average. The set can grow to n values.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["It spends O(n) extra memory to finish in a single pass."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-seen-set","title":"Start with an empty set","description":"Create the empty set that will hold every number the scan has passed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"initializes_set_state","scope":"convert-to-set","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Creating the set inside the loop, which empties it again for every number","Using a list, where each lookup reads through the earlier numbers one by one"],"hint":"The set has to exist before the loop starts, so it still holds the earlier numbers when a later one is looked up.","semanticSpec":{"intent":"Initialize reusable membership state.","doneWhen":"A set-like state is created before checking values.","shouldFailWhen":"This step should fail if no set state exists.","roles":["seen set"],"mustProve":["The solution initializes set-membership state."],"mustNotAccept":["A membership structure that is recreated for each value."],"proofSnippets":[{"id":"py-contains-duplicate-init-seen-set","language":"python","code":"class Solution:\n    def containsDuplicate(self, nums: list[int]) -> bool:\n        seen = set()"}]}},{"id":"scan-values","title":"Go through the numbers","description":"Loop over the list from the first number to the last, one number at a time.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Comparing only neighbors, which misses a repeat that sits further apart"],"hint":"A repeat can sit anywhere in the list, so the loop moves one position at a time, without jumping ahead.","semanticSpec":{"intent":"Traverse the input values.","doneWhen":"The solution loops over `nums`.","shouldFailWhen":"This step should fail if the input sequence is not scanned.","roles":["input sequence","current value"],"mustProve":["The traversal reads the input sequence."],"mustNotAccept":["A fixed comparison unrelated to `nums`."],"proofSnippets":[{"id":"py-contains-duplicate-scan-values","language":"python","code":"class Solution:\n    def containsDuplicate(self, nums: list[int]) -> bool:\n        seen = set()\n        for num in nums:\n            pass"}]}},{"id":"check-seen","title":"Return true on a repeat","description":"Look the current number up in the set. If it is already there, return true.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"workflow","scope":"return-duplicate","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Adding the number before looking it up, so that it finds its own copy"],"hint":"A number that is already in the set has appeared earlier in the list, and one repeat is all the answer needs.","semanticSpec":{"intent":"Use set membership to return true for repeated values.","doneWhen":"The current value is checked against the seen set and the membership-hit branch returns true before insertion.","shouldFailWhen":"This step should fail if the membership-hit branch does not return true.","roles":["current value","seen set"],"mustProve":["The solution returns true from the membership-hit branch."],"mustNotAccept":["A comparison against the current value itself.","A membership check whose hit branch does not return true."],"proofSnippets":[{"id":"py-contains-duplicate-check-seen","language":"python","code":"class Solution:\n    def containsDuplicate(self, nums: list[int]) -> bool:\n        seen = set()\n        for num in nums:\n            if num in seen:\n                return True"}]}},{"id":"record-value","title":"Add the number to the set","description":"When the lookup misses, add the current number to the set so that later numbers can find it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"adds_member_to_set","scope":"add-edge","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Leaving the add out, so the set stays empty and no lookup ever finds anything"],"hint":"A number that is new now may come up again later in the list.","semanticSpec":{"intent":"Persist current values for future membership checks.","doneWhen":"This step is done when each value that is not already seen is inserted into the seen set.","shouldFailWhen":"This step should fail if new values are never recorded.","roles":["current value","seen set"],"mustProve":["The solution writes membership state during the scan."],"mustNotAccept":["A no-op after the membership check."],"proofSnippets":[{"id":"py-contains-duplicate-record-value","language":"python","code":"class Solution:\n    def containsDuplicate(self, nums: list[int]) -> bool:\n        seen = set()\n        for num in nums:\n            if num in seen:\n                return True\n            seen.add(num)"}]}},{"id":"return-no-duplicate","title":"Return false after the loop","description":"If the loop finishes without finding a repeat, return false.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"workflow","scope":"return-no-duplicate","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Leaving out the final return, so a list with no repeat gets no answer"],"hint":"Getting past the last number means every lookup missed.","semanticSpec":{"intent":"Return the no-duplicate verdict after the seen-set scan completes.","doneWhen":"The scan has a completed no-duplicate path that returns false after recording unseen values.","shouldFailWhen":"This step should fail if the completed scan does not return false.","roles":["seen set","return value"],"mustProve":["The scan has a completed no-duplicate path that returns false."],"mustNotAccept":["Ending the function without a false result path.","Returning true after the scan completes."],"proofSnippets":[{"id":"py-contains-duplicate-return-no-duplicate","language":"python","code":"class Solution:\n    def containsDuplicate(self, nums: list[int]) -> bool:\n        seen = set()\n        for num in nums:\n            if num in seen:\n                return True\n            seen.add(num)\n        return False"}]}},{"id":"return-duplicate-verdict","title":"Return each answer in the right place","description":"True is returned from inside the loop, at the first number already in the set. False is returned only after the loop has finished.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_guarded_boolean_decision","scope":"return-duplicate-verdict","readMode":"array-scan-value-query-v1","expected":{"hitValue":true,"missValue":false}}]},"commonMistakes":["Returning false inside the loop, at the first number that is not in the set","Swapping the two answers, so that a repeat returns false"],"hint":"One repeat is enough for true. False is a claim about every number, so it has to wait for the last one.","semanticSpec":{"intent":"Return true on the duplicate hit path and false after the scan has found no duplicate.","doneWhen":"The in-loop hit path returns true and the after-loop miss path returns false.","shouldFailWhen":"The code returns false on a hit, returns true after a clean scan, or has only one verdict path.","roles":["current num","seen set","boolean result"],"mustProve":["The duplicate hit branch returns true during the scan.","The completed scan returns false after no hit is found."],"mustNotAccept":["Returning false from the first membership miss.","Returning true after the loop when no duplicate was found."],"proofSnippets":[{"id":"py-contains-duplicate-return-duplicate-verdict","language":"python","code":"class Solution:\n    def containsDuplicate(self, nums: list[int]) -> bool:\n        seen = set()\n        for num in nums:\n            if num in seen:\n                return True\n            seen.add(num)\n        return False"}]}}],"slides":[{"id":"the-task","kind":"info","title":"Does any number in the list appear more than once?","workspacePanel":"problem","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example","state":{"nums":[1,2,3,1]}}]},"body":["You are given a list of integers. Return true if any number appears in it more than once, and false if every number is different.","In the list drawn here, 1 appears twice, so the answer is true."]},{"id":"look-back","kind":"info","title":"Look back from each number","workspacePanel":"visualizer","body":["Go through the list from left to right. At each number, compare it with every earlier number, and stop at the first match."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"compare-1","title":"2 is compared with 1","summary":"They differ. Nothing else comes before 2, so the scan moves on to 3.","state":{"nums":[1,2,3,1],"i":1,"j":0,"labels":{"i":"num","j":"earlier"}}},{"id":"compare-2","title":"3 is compared with 1","summary":"They differ, and one more number comes before 3.","state":{"nums":[1,2,3,1],"i":2,"j":0,"labels":{"i":"num","j":"earlier"}}},{"id":"compare-3","title":"3 is compared with 2","summary":"They differ as well, so the scan moves on to the last number.","state":{"nums":[1,2,3,1],"i":2,"j":1,"labels":{"i":"num","j":"earlier"}}},{"id":"compare-4","title":"The last 1 is compared with the first 1","summary":"They match. After 4 comparisons the answer is true.","state":{"nums":[1,2,3,1],"i":3,"j":0,"labels":{"i":"num","j":"earlier"}}}]}},{"id":"look-back-cost","kind":"case-probe","title":"Now a list with no repeat. How many comparisons does looking back make before it can return false?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-repeat","state":{"nums":[1,2,3,4]}}]},"options":[{"id":"three","label":"3","rationale":"That would be one comparison for each number after the first. The third number has two numbers before it and the fourth has three, and each of those gets compared.","isCorrect":false},{"id":"four","label":"4","rationale":"That was the count for 1, 2, 3, 1, where a match ended the scan early. Nothing matches here, so each number is compared with all the earlier ones.","isCorrect":false},{"id":"six","label":"6","rationale":"The second number is compared with one earlier number, the third with two, and the fourth with three: 1 + 2 + 3 = 6. A list of 100,000 numbers, the longest this problem allows, would take about 5 billion.","isCorrect":true},{"id":"twelve","label":"12","rationale":"That counts every pair twice. Once the second number has been compared with the first, the first is never compared with the second again.","isCorrect":false}]},{"id":"state-quiz","kind":"case-probe","title":"Suppose the scan kept something as it went. What could it keep so that, at the last 1, it never has to look back?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"on-last-number","state":{"nums":[1,2,3,1],"i":3,"labels":{"i":"num"}}}]},"options":[{"id":"values-passed","label":"The values it has already passed","rationale":"Those are 1, 2 and 3. The current 1 is among them, so it is a repeat, and no earlier number had to be read again. Where each value sat is never needed, only whether it has come up.","isCorrect":true},{"id":"previous-value","label":"Only the value just before this one","rationale":"That is 3. The matching 1 sits three places back, and a repeat can be any distance away.","isCorrect":false},{"id":"largest-value","label":"The largest value so far","rationale":"That is 3 as well, and it says nothing about whether a 1 has come up.","isCorrect":false},{"id":"count-passed","label":"How many numbers it has passed","rationale":"That is 3, and it would be 3 for any three numbers. A count does not say which values went by.","isCorrect":false}]},{"id":"seen-set","kind":"info","title":"Keep the earlier values in a hash set","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-seen","state":{"nums":[1,2,3,1],"seenSet":[]}}]},"body":["A hash set is a collection of values that can answer one question quickly: is this value in it? That check is called a lookup. It takes about one step on average, however many values the set holds.","A second plain list would not help. Finding a value in a list means reading through it, which is looking back all over again.","Call the set `seen`, and start it empty."]},{"id":"trace","kind":"dry-run","source":"trace-example","title":"1, 2, 3, 1 again, this time with `seen`","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-number","state":{"nums":[1,2,3,1],"i":0,"seenSet":[],"seenHighlight":1,"labels":{"i":"num"}}},{"id":"second-number","state":{"nums":[1,2,3,1],"i":1,"seenSet":[1],"seenHighlight":2,"labels":{"i":"num"}}},{"id":"last-number","state":{"nums":[1,2,3,1],"i":3,"seenSet":[1,2,3],"seenHighlight":1,"labels":{"i":"num"}}},{"id":"repeat-found","state":{"nums":[1,2,3,1],"i":3,"seenSet":[1,2,3],"seenHighlight":1,"labels":{"i":"num"},"result":true}}]},"beats":[{"id":"first-number","title":"The lookup for the first 1 finds nothing, because `seen` is empty. What does the scan do next?","options":[{"id":"add-and-continue","label":"It adds 1 to `seen` and moves on to 2","rationale":"Another 1 is still ahead. It can only be caught if this one is in the set when it arrives.","isCorrect":true},{"id":"return-false","label":"It returns false, because nothing matched 1","rationale":"Nothing before this 1 matches it. Three numbers are still unread, though, and the last of them is another 1.","isCorrect":false},{"id":"continue-without-adding","label":"It moves on to 2 and leaves `seen` empty","rationale":"Then the last 1 would find no 1 in the set and pass as new.","isCorrect":false}]},{"id":"second-number","title":"2 and 3 are read next. What does `seen` hold once both have been read?","options":[{"id":"all-three","label":"1, 2 and 3","rationale":"Each lookup misses, so each number is added. Nothing is ever taken out, so the 1 from the start is still there.","isCorrect":true},{"id":"two-and-three","label":"2 and 3","rationale":"Adding 2 and 3 does not push the 1 out. The set keeps every number the scan has passed.","isCorrect":false},{"id":"only-three","label":"Only 3","rationale":"The set holds more than the latest number. If it kept only 3, the last 1 would have nothing to match.","isCorrect":false}]},{"id":"last-number","title":"The scan is on the last 1, and `seen` holds 1, 2 and 3. What does the scan do with this 1?","options":[{"id":"return-true","label":"It finds 1 in `seen` and returns true","rationale":"A number that is already in the set has appeared earlier in the list, and that is all the problem asks about.","isCorrect":true},{"id":"skip-and-finish","label":"It finds 1 in `seen`, skips it, and returns false","rationale":"Finding 1 there is the repeat the scan was looking for. Skipping it throws the answer away.","isCorrect":false},{"id":"add-again","label":"It adds 1 to `seen` a second time and returns false","rationale":"The lookup runs before the add, and it finds 1. The scan returns true without adding anything.","isCorrect":false}]}]},{"id":"edge-case-intro","kind":"info","title":"In 1, 2, 3, 1 the repeat was the last number. Three more lists come next.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"walkthrough-end","state":{"nums":[1,2,3,1],"i":3,"seenSet":[1,2,3],"seenHighlight":1,"labels":{"i":"num"}}}]},"body":["So the scan found the repeat and reached the end at the same moment, which hides what makes it stop.","The first of the next lists has a repeat right at the start. The second has no repeat at all. The third holds a single number.","Where does the scan stop on each one?"]},{"id":"early-return-probe","kind":"case-probe","title":"The first list has ten numbers. How many does the scan read before it returns?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ten-numbers","state":{"nums":[1,1,1,3,3,4,3,2,4,2],"seenSet":[]}}]},"options":[{"id":"one","label":"1","rationale":"One number alone cannot be a repeat. The first 1 misses on the empty set and is added.","isCorrect":false},{"id":"two","label":"2","rationale":"The first 1 goes into `seen`. The second 1 is found there, and the scan returns true with eight numbers unread.","isCorrect":true},{"id":"three","label":"3","rationale":"The scan never gets to the third 1. The second 1 already repeats the first.","isCorrect":false},{"id":"ten","label":"10","rationale":"Nothing in the last eight numbers can undo the repeat at the start, so reading them changes nothing.","isCorrect":false}]},{"id":"all-distinct-probe","kind":"case-probe","title":"The second list is 1, 2, 3, 4, with no repeat. How many numbers does the scan read before it can return false?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"four-numbers","state":{"nums":[1,2,3,4],"seenSet":[]}}]},"options":[{"id":"one","label":"1","rationale":"One miss shows only that nothing came before the first number. The other three are still unread.","isCorrect":false},{"id":"three","label":"3","rationale":"That leaves the last number unread. Had it been another 1, the answer would be true.","isCorrect":false},{"id":"four","label":"4","rationale":"Until the 4 has been looked up, it could still turn out to repeat an earlier number. That is 4 lookups, one per number, where looking back needed 6 comparisons on this same list.","isCorrect":true}]},{"id":"single-number-probe","kind":"case-probe","title":"The last list holds a single number, 7. What does the scan do with it?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"one-number","state":{"nums":[7],"seenSet":[]}}]},"options":[{"id":"returns-false","label":"It returns false: 7 misses and the list ends","rationale":"7 is looked up in the empty set, misses, and is added. Then the list runs out, which is when false is returned.","isCorrect":true},{"id":"returns-true","label":"It returns true: 7 ends up in `seen`","rationale":"7 is in the set only because it was added after its own lookup missed. No lookup ever found anything.","isCorrect":false},{"id":"fails","label":"It fails: 7 has nothing to compare with","rationale":"The first number of every list is looked up in an empty set. That lookup misses and the scan carries on.","isCorrect":false}]},{"id":"order-intro","kind":"info","title":"So far the lookup has always come before the add","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"swap-start","state":{"nums":[1,2,3,4],"seenSet":[]}}]},"body":["The two steps could go the other way round: add the number to `seen` first, then look it up. That order looks just as reasonable.","Try it on 1, 2, 3, 4, the list with no repeat."]},{"id":"list-pitfall","kind":"case-probe","title":"The swapped version has added the first 1 to `seen`. What does its lookup find?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"added-first","state":{"nums":[1,2,3,4],"i":0,"seenSet":[1],"labels":{"i":"num"}}}]},"options":[{"id":"own-copy","label":"The 1 it just added, so the scan returns true","rationale":"A number's own copy looks no different from an earlier one. This list has no repeat, yet the swapped version answers true after one number. The same happens to the first number of any list, so it returns true every time.","isCorrect":true},{"id":"nothing-earlier","label":"Nothing, because no earlier number was a 1","rationale":"That is what the lookup finds when it runs before the add. In this version the 1 is already in the set when the lookup runs.","isCorrect":false},{"id":"hit-but-continue","label":"The 1 it just added, but the scan carries on because nothing has repeated","rationale":"A hit is the only sign of a repeat the scan has, and nothing marks this one as the number's own copy.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"That is the whole scan. Time to write it as a function.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[1,2,3,1],"seenSet":[]}}]},"body":["The function starts with an empty set and reads the list once, from the first number to the last.","For each number, it looks the number up in the set first. If the number is already there, it has appeared before, and the function returns true right away. If not, the function adds it to the set and moves on.","If the function reaches the end of the list without finding a repeat, it returns false."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Write the scan","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"Finding a repeat in one pass","workspacePanel":"code","takeaways":[{"title":"Look each number up among the earlier ones","body":"`seen` holds every number the scan has passed, so one lookup does the work of looking back through the list."},{"title":"Look up first, then add","body":"Added first, a number finds its own copy in the set and is reported as a repeat."},{"title":"True can come early, false only at the end","body":"The first number found in the set is enough for true. False needs every number in the list to have missed."},{"title":"O(n) time, O(n) space","body":"Each of the n numbers costs one lookup and at most one add, which is O(n) time on average. `seen` can grow to n values, so it takes O(n) extra space. Looking back used no extra space but up to about n²/2 comparisons."}]}],"slidesOrigin":"authored","progressRevision":"contains-duplicate-2026-11-20-look-back-to-seen-set"}}
