{"id":"contains-duplicate-ii","title":"Contains Duplicate II","difficulty":"easy","patterns":["sliding-window"],"primaryConcept":"array-sliding-window-fixed","concepts":["array-sliding-window-fixed","hash-map-grouping"],"problemForm":"intro","companies":["Amazon","Google","Microsoft"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array-scalar","primaryParam":"nums","sizeMetric":"length","sizes":[8,16,32,64],"valueRange":{"min":0,"max":20},"secondaryParams":{"k":{"strategy":"proportion","proportion":0.3}}},"description":"Given an integer array `nums` and an integer `k`, return `true` if there are two distinct indices `i` and `j` such that `nums[i] == nums[j]` and `abs(i - j) <= k`. Otherwise, return `false`.","examples":[{"input":"nums = [1,2,3,1], k = 3","output":"true","explanation":"The two 1 values are three positions apart, which is allowed."},{"input":"nums = [1,2,3,1,2,3], k = 2","output":"false","explanation":"Each repeated value is more than two positions away."}],"constraints":[{"id":"1-len-nums-100000","text":"1 <= len(nums) <= 100000","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":100000}},{"id":"1000000000-nums-i-1000000000","text":"-1000000000 <= nums[i] <= 1000000000","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-1000000000,"max":1000000000}},{"id":"0-k-100000","text":"0 <= k <= 100000"}],"starterCode":"class Solution:\n    def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:\n        # Your code here\n        pass","functionName":"containsNearbyDuplicate","testCases":[{"id":"1","input":{"nums":[1,2,3,1],"k":3},"expected":true,"description":"Duplicate inside the allowed distance."},{"id":"2","input":{"nums":[1,0,1,1],"k":1},"expected":true,"description":"Adjacent duplicate after an earlier expired value."},{"id":"3","input":{"nums":[1,2,3,1,2,3],"k":2},"expected":false,"description":"Duplicates exist but all are too far apart."},{"id":"4","input":{"nums":[5,5],"k":0},"expected":false,"description":"A zero-width window cannot match two distinct indices."},{"id":"h1","input":{"nums":[1,2,3,1],"k":2},"expected":false},{"id":"h2","input":{"nums":[1,2,3,4,1],"k":3},"expected":false},{"id":"h3","input":{"nums":[-1,-2,-3,-1],"k":3},"expected":true},{"id":"h4","input":{"nums":[1,2,1,2],"k":1},"expected":false},{"id":"h5","input":{"nums":[99],"k":1},"expected":false},{"id":"h6","input":{"nums":[1,0,1,1],"k":2},"expected":true}],"hints":[{"level":1,"content":"Only values from the last k positions can match the current value."},{"level":2,"content":"Use a set as a rolling window of recent values."},{"level":3,"content":"Check membership before adding the current value, then remove the value that just fell out of range."}],"guidedFlow":{"version":2,"progressRevision":"contains-duplicate-ii-2026-11-20-sliding-set-rewrite","approachSelection":{"contract":"approach-selection-v1","question":"Which method should the function use?","decisionPrompt":"Compare what each one costs for every new value.","approaches":[{"id":"look-back","name":"Look back k positions","summary":"For each value, compare it with each value at most k positions before it.","decisionReason":"Each value costs up to k comparisons, so n values cost up to n × k. With 100,000 values and k = 50,000 that is several billion.","complexity":{"time":"O(n × k)","space":"O(1)"},"tradeoffs":["Uses no extra memory, but needs up to n × k comparisons."],"isOptimal":false},{"id":"rolling-set","name":"Set of the last k values","summary":"Scan once with a set that holds only the values from the previous k indices.","decisionReason":"Each value costs one lookup, one add and at most one removal, so the scan is O(n). The set never holds more than k + 1 values, which is O(min(n, k + 1)) space.","complexity":{"time":"O(n)","space":"O(min(n, k + 1))"},"tradeoffs":["Runs in O(n) time and uses O(min(n, k + 1)) extra space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"scan-with-index","title":"Scan the list with its indices","description":"Go through nums one value at a time, keeping each value's index alongside it.","commonMistakes":["Looping over the values alone, which loses the index needed to find the value k positions back."],"hint":"The index is how you will find the value k positions back later on.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence_with_index","scope":"loop-with-index","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Scan the input values together with their positions.","doneWhen":"The loop reads both the current value and its index.","shouldFailWhen":"The solution cannot tell which old index should expire.","roles":["index","current value"],"mustProve":["The solution performs an indexed scan over the input sequence."],"mustNotAccept":["A scan that has no index state for window expiration."],"proofSnippets":[{"id":"py-contains-duplicate-ii-scan-with-index","language":"python","code":"class Solution:\n    def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:\n        for i, num in enumerate(nums):\n            pass"}]}},{"id":"check-recent-duplicate","title":"Return true on a hit","description":"Start with an empty set of recent values. Inside the loop, look up the current value in it and return true if it is there.","commonMistakes":["Adding the current value before looking it up, so every value matches itself.","Finding the value in the set but not returning true from that branch."],"hint":"Create the set before the loop, so it carries over from one value to the next.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"workflow","scope":"return-duplicate","readMode":"set-membership-value-query-v1"}]},"semanticSpec":{"intent":"Use set membership to return true for a duplicate still inside the allowed distance.","doneWhen":"The current value is checked against the recent set and the membership-hit branch returns true before insertion.","shouldFailWhen":"The membership-hit branch does not return true.","roles":["current value","recent set"],"mustProve":["The solution returns true from the recent-set membership-hit branch."],"mustNotAccept":["A membership check against an unrelated collection.","A membership check whose hit branch does not return true."],"proofSnippets":[{"id":"py-contains-duplicate-ii-check-recent-duplicate","language":"python","code":"class Solution:\n    def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:\n        seen = set()\n        for i, num in enumerate(nums):\n            if num in seen:\n                return True"}]}},{"id":"add-current-value","title":"Add the current value","description":"After a miss, add the current value to the set so any of the next k values can match it.","commonMistakes":["Leaving the add inside the hit branch, where it never runs for a value that missed."],"hint":"This goes after the lookup, in the same pass of the loop.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"writes_set_membership_state","scope":"add-edge","readMode":"set-membership-value-query-v1"}]},"semanticSpec":{"intent":"Write the current value into the rolling membership state.","doneWhen":"Each value that does not immediately return true is added to the recent set.","shouldFailWhen":"The code never records current values for later indices.","roles":["current value","recent set"],"mustProve":["The solution writes set-membership state during the scan."],"mustNotAccept":["A no-op after the membership check."],"proofSnippets":[{"id":"py-contains-duplicate-ii-add-current-value","language":"python","code":"class Solution:\n    def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:\n        seen = set()\n        for i, num in enumerate(nums):\n            if num in seen:\n                return True\n            seen.add(num)"}]}},{"id":"evict-expired-value","title":"Remove the value that fell out of reach","description":"After the add, remove the value k positions behind the current index, once the scan is far enough along for one to exist.","commonMistakes":["Being off by one about which value leaves. After the value at index i is added, the one at index i - k is out of reach for index i + 1.","Never removing anything, so a repeat that is too far apart still produces a hit."],"hint":"Below index k there is no value k positions back, so nothing is removed there.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"writes_set_membership_state","scope":"remove-member","readMode":"set-membership-value-query-v1"}]},"semanticSpec":{"intent":"Keep the set limited to values that may still match future indices.","doneWhen":"This step is done when expired values are removed as the window advances.","shouldFailWhen":"The solution never removes old values from the recent set.","roles":["expired value","recent set"],"mustProve":["The solution removes members from set state as the window advances."],"mustNotAccept":["A set that keeps every previous value forever."],"proofSnippets":[{"id":"py-contains-duplicate-ii-evict-expired-value","language":"python","code":"class Solution:\n    def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:\n        seen = set()\n        for i, num in enumerate(nums):\n            if num in seen:\n                return True\n            seen.add(num)\n            if i >= k:\n                seen.remove(nums[i - k])"}]}},{"id":"return-no-nearby-duplicate","title":"Return false after the scan","description":"If the loop ends without a hit, no value repeats within k positions, so return false.","commonMistakes":["Returning false inside the loop on the first miss, before later values are looked up."],"hint":"This return sits after the loop, where it runs only when every lookup missed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"workflow","scope":"return-no-duplicate","readMode":"set-membership-value-query-v1"}]},"semanticSpec":{"intent":"Return the no-nearby-duplicate verdict after the bounded seen-set scan completes.","doneWhen":"The scan has a completed no-nearby-duplicate path that returns false after recording checked values.","shouldFailWhen":"The completed scan does not return false.","roles":["recent set","return value"],"mustProve":["The scan has a completed no-nearby-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-ii-return-no-nearby-duplicate","language":"python","code":"class Solution:\n    def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:\n        seen = set()\n        for i, num in enumerate(nums):\n            if num in seen:\n                return True\n            seen.add(num)\n            if i >= k:\n                seen.remove(nums[i - k])\n        return False"}]}},{"id":"return-nearby-duplicate-verdict","title":"Return the right result on both paths","description":"True comes from the hit inside the loop, and false comes only after the whole list has been scanned.","commonMistakes":["Swapping the two results, so a hit returns false and a finished scan returns true."],"hint":"A hit proves the answer at once. A miss proves nothing until the last value has been looked up.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_guarded_boolean_decision","scope":"return-nearby-duplicate-verdict","readMode":"array-scan-value-query-v1","expected":{"hitValue":true,"missValue":false}}]},"semanticSpec":{"intent":"Return true on the bounded duplicate hit path and false after no nearby duplicate is found.","doneWhen":"The in-loop hit path returns true and the after-loop miss path returns false.","shouldFailWhen":"The code returns false on a nearby hit, returns true after a clean scan, or has only one verdict path.","roles":["current num","recent set","boolean result"],"mustProve":["The nearby duplicate hit branch returns true during the scan.","The completed bounded scan returns false after no hit is found."],"mustNotAccept":["Returning false from the first membership miss.","Returning true after the loop when no nearby duplicate was found."],"proofSnippets":[{"id":"py-contains-duplicate-ii-return-nearby-duplicate-verdict","language":"python","code":"class Solution:\n    def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:\n        seen = set()\n        for i, num in enumerate(nums):\n            if num in seen:\n                return True\n            seen.add(num)\n            if i >= k:\n                seen.remove(nums[i - k])\n        return False"}]}}],"slides":[{"id":"the-task","kind":"info","title":"Find a value that repeats close by","workspacePanel":"problem","body":["You get a list of numbers and a distance, k. Each number's position in the list is called its index, counting from 0. Two copies at indices 1 and 3 are 2 positions apart.","Return true if some value appears twice with its two copies at most k positions apart. If no value does, return false."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example","state":{"nums":[4,1,2,4,2],"k":2}}]}},{"id":"first-example","kind":"case-probe","title":"What should this list return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example","state":{"nums":[4,1,2,4,2],"k":2}}]},"options":[{"id":"true-twos","label":"True, because of the two 2s","rationale":"The 2s sit at indices 2 and 4, which is 2 apart. A gap of exactly k still counts.","isCorrect":true},{"id":"true-fours","label":"True, because of the two 4s","rationale":"The 4s sit at indices 0 and 3. That is 3 apart and k is 2, so this pair is too far apart to count.","isCorrect":false},{"id":"false-none","label":"False, because no pair is close enough","rationale":"The 4s are too far apart, but the 2s at indices 2 and 4 are exactly 2 apart, and at most k includes k itself.","isCorrect":false}]},{"id":"window-probe","kind":"case-probe","title":"Reading left to right, you reach the 4 at index 3. Which earlier indices are close enough to pair with it?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"reach-from-3","state":{"nums":[4,1,2,4,2],"k":2,"i":3}}]},"options":[{"id":"previous-k","label":"Indices 1 and 2","rationale":"With k = 2, a partner sits at most 2 positions back. From index 3 that is index 2 or index 1. Index 0 is already too far, and every later index is even further from it.","isCorrect":true},{"id":"all-earlier","label":"Indices 0, 1 and 2","rationale":"Index 0 is 3 positions back from index 3, and k is 2. Whatever sits there is too far away to count.","isCorrect":false},{"id":"neighbor-only","label":"Index 2 only","rationale":"k = 2 allows a gap of 2 as well as a gap of 1, so index 1 is also within reach.","isCorrect":false}]},{"id":"brute-force","kind":"info","title":"Look back up to k positions from each value","workspacePanel":"visualizer","body":["That gives a direct method: when you reach the value at index i, compare it with each value at most k positions before it, and return true on the first match."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"look-back-3","title":"No match at index 3","summary":"The 4 is compared with the 2 at index 2 and then the 1 at index 1. Neither is a 4.","state":{"nums":[4,1,2,4,2],"k":2,"i":3,"left":1,"right":3,"labels":{"left":"","right":""}}},{"id":"look-back-4","title":"A match at index 4","summary":"The 2 is compared with the 4 at index 3 and then the 2 at index 2. Those are equal, so the method returns true.","state":{"nums":[4,1,2,4,2],"k":2,"i":4,"left":2,"right":4,"labels":{"left":"","right":""}}}]}},{"id":"waste-probe","kind":"case-probe","title":"Now take a long list: 100,000 values and k = 50,000. About how many comparisons can this method need?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"look-back-cost","state":{"nums":[4,1,2,4,2],"k":2,"i":4,"left":2,"right":4,"labels":{"left":"","right":""}}}]},"options":[{"id":"about-n","label":"About 100,000","rationale":"That would be one comparison per value. Here a single value can be compared with up to 50,000 earlier ones.","isCorrect":false},{"id":"about-n-plus-k","label":"About 150,000","rationale":"That adds the two numbers. Every value does its own looking back, so they multiply.","isCorrect":false},{"id":"billions","label":"Several billion","rationale":"When nothing matches, each of the last 50,000 values looks back 50,000 positions. That alone is 2.5 billion comparisons.","isCorrect":true}]},{"id":"set-attempt","kind":"info","title":"Can a set of every value so far replace the look-back?","workspacePanel":"visualizer","body":["Every look-back asks the same question: is this value somewhere among the earlier ones?","A set is a collection of values that answers that kind of question quickly. Checking whether a set holds a 4 takes about one step, however many values are in it.","A first try: keep every value you have read in a set called `seen`, and look up each new value there before adding it. A hit means the value appeared earlier.","Try it on the first four values of the list, where the right answer is false: the only repeat is the 4s, and they are 3 apart."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"keep-all-start","state":{"nums":[4,1,2,4],"k":2,"seenSet":[]}}]}},{"id":"no-evict-pitfall","kind":"dry-run","source":"trace-example","title":"A set that keeps every value","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"keep-all-setup","state":{"nums":[4,1,2,4],"k":2,"i":3,"seenSet":[4,1,2]}},{"id":"keep-all-lookup","state":{"nums":[4,1,2,4],"k":2,"i":3,"seenSet":[4,1,2],"seenHighlight":4}},{"id":"keep-all-fix","state":{"nums":[4,1,2,4],"k":2,"i":3,"seenSet":[1,2],"seenHighlight":4}}]},"beats":[{"id":"keep-all-lookup","title":"The 4 at index 3 arrives. What does this version do?","options":[{"id":"returns-true","label":"Finds a 4 in the set and returns true","rationale":"The set still holds the 4 from index 0, so the lookup hits. The function returns true on a list whose answer is false.","isCorrect":true},{"id":"moves-on","label":"Finds no 4 within reach and moves on","rationale":"Reach plays no part in this version. The set holds 4, 1 and 2, so a lookup for 4 hits.","isCorrect":false},{"id":"checks-distance","label":"Finds a 4, then checks how far back it is","rationale":"The set stores values only. It has no index for the old 4, so there is no distance to check.","isCorrect":false}]},{"id":"keep-all-fix","title":"What should the set have held when that 4 arrived?","options":[{"id":"in-reach","label":"Only the 1 and the 2, from indices 1 and 2","rationale":"Those are the only values index 3 can pair with. A set holding just them misses on 4, and the answer comes out false.","isCorrect":true},{"id":"all-three","label":"The 4, the 1 and the 2, as it did","rationale":"Those contents produced the wrong hit. The 4 from index 0 is 3 positions back, out of reach for index 3.","isCorrect":false},{"id":"nothing","label":"Nothing, so that no lookup can hit","rationale":"An empty set also misses real matches. If index 3 held a 2, the 2 at index 2 would have to be in the set to be found.","isCorrect":false}]}]},{"id":"evict-probe","kind":"case-probe","title":"Back on the full list, the scan moves from index 3 to index 4. What is the least the set has to change?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"between-3-and-4","state":{"nums":[4,1,2,4,2],"k":2,"i":3,"seenSet":[1,2]}}]},"options":[{"id":"one-in-one-out","label":"Add the 4 from index 3 and remove the 1 from index 1","rationale":"The value at index 4 can only pair with indices 2 and 3. The 4 at index 3 has just come into that range, and the 1 at index 1 has just dropped out. In general, after the value at index i is added, the one at index i - k leaves.","isCorrect":true},{"id":"add-only","label":"Add the 4 from index 3 and remove nothing","rationale":"Then the set holds the 1 from index 1, which is 3 positions behind index 4. That is the keep-everything mistake again.","isCorrect":false},{"id":"rebuild","label":"Empty it, then add the values at indices 2 and 3","rationale":"That rebuilds k values at every index, which costs as much as looking back did. At most two values change from one index to the next.","isCorrect":false}]},{"id":"dry-run-setup","kind":"info","title":"The whole list, starting from an empty set","workspacePanel":"visualizer","body":["A lookup that hits returns true at once. After a miss, the value is added, and then the value k positions behind it leaves, if there is one. At index 0 the 4 misses on the empty set and goes in."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-index-0","state":{"nums":[4,1,2,4,2],"k":2,"i":0,"seenSet":[4]}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Trace the set across the list","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"nums":[4,1,2,4,2],"k":2,"i":1,"seenSet":[4]}},{"id":"arrive-1","state":{"nums":[4,1,2,4,2],"k":2,"i":2,"seenSet":[4,1]}},{"id":"arrive-2","state":{"nums":[4,1,2,4,2],"k":2,"i":3,"seenSet":[1,2]}},{"id":"arrive-far-4","state":{"nums":[4,1,2,4,2],"k":2,"i":4,"seenSet":[2,4]}},{"id":"arrive-near-2","state":{"nums":[4,1,2,4,2],"k":2,"i":4,"seenSet":[2,4],"seenHighlight":2}}]},"beats":[{"id":"arrive-1","title":"The 1 at index 1 arrives. What does the set hold when index 2 arrives?","options":[{"id":"four-and-one","label":"4 and 1","rationale":"The lookup for 1 misses on a set holding only 4, so the 1 goes in. Nothing leaves, because index 1 - 2 does not exist, so the 4 stays.","isCorrect":true},{"id":"one-only","label":"Only 1","rationale":"The 4 at index 0 is 2 positions behind index 2, which is still within k. It has to stay for that lookup.","isCorrect":false},{"id":"four-only","label":"Only 4","rationale":"Then the lookup for a later 1 could never find this one. Every value that misses is added.","isCorrect":false}]},{"id":"arrive-2","title":"The 2 at index 2 arrives. What does the set hold when index 3 arrives?","options":[{"id":"one-and-two","label":"1 and 2","rationale":"The 2 misses and goes in. Then the value at index 2 - 2 = 0 leaves, which takes out the 4.","isCorrect":true},{"id":"all-three","label":"4, 1 and 2","rationale":"That keeps the 4 from index 0, which is 3 positions behind index 3. The next lookup would hit it.","isCorrect":false},{"id":"four-and-two","label":"4 and 2","rationale":"The value that leaves is the one at index 2 - 2 = 0. The 1 at index 1 is still within reach of index 3.","isCorrect":false}]},{"id":"arrive-far-4","title":"The 4 at index 3 arrives. What does the lookup find?","options":[{"id":"miss","label":"No 4, so the scan goes on","rationale":"The 4 from index 0 left one step ago. The set holds 1 and 2, so the lookup misses. Then the 4 goes in, and the 1 from index 3 - 2 = 1 leaves.","isCorrect":true},{"id":"hit","label":"A 4, so it returns true","rationale":"That is what the keep-everything version did. Here the 4 from index 0 was removed before this lookup.","isCorrect":false},{"id":"too-far","label":"A 4 that is too far back to count","rationale":"The set stores no positions. The old 4 is no longer in it, so the lookup finds nothing.","isCorrect":false}]},{"id":"arrive-near-2","title":"The 2 at index 4 arrives. What does the lookup find?","options":[{"id":"hit","label":"A 2, so it returns true","rationale":"The 2 from index 2 is exactly 2 positions back and is still in the set. Everything in the set is within k, so a hit needs no distance check.","isCorrect":true},{"id":"already-left","label":"No 2, because the earlier one has left","rationale":"A value leaves only after the lookup k positions later. The 2 from index 2 is still there for the lookup at index 4.","isCorrect":false},{"id":"measure","label":"A 2, and then it measures the gap","rationale":"There is nothing to measure. The set holds values from the last 2 indices only, so any hit is close enough.","isCorrect":false}]}]},{"id":"add-before-lookup","kind":"case-probe","title":"Suppose each value were added to the set before its lookup. What would the lookup for the 4 at index 0 find?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"added-first","state":{"nums":[4,1,2,4,2],"k":2,"i":0,"seenSet":[4]}}]},"options":[{"id":"finds-itself","label":"That same 4, so the function returns true at once","rationale":"The 4 is already in the set when its own lookup runs, so every list would return true at index 0. Looking up before adding makes sure a hit comes from an earlier index.","isCorrect":true},{"id":"finds-nothing","label":"Nothing, because the set starts out empty","rationale":"The set is empty before index 0, but in this order the 4 goes in first and its own lookup then finds it.","isCorrect":false},{"id":"finds-later-four","label":"The 4 from index 3","rationale":"Index 3 has not been read yet. The only 4 in the set is the one that just went in.","isCorrect":false}]},{"id":"edge-case-intro","kind":"info","title":"The rule worked with k = 2. Next, the smallest k and one larger than the list.","workspacePanel":"visualizer","body":["The first list has k = 0, the smallest distance there is. The second has k = 10 on a list of only four values.","Does the same rule give the right answer on both?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"k-zero-start","state":{"nums":[5,5],"k":0,"seenSet":[]}}]}},{"id":"k-zero-probe","kind":"case-probe","title":"In the first list, k is 0, and the first 5 has just been added. Which value leaves the set?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"k-zero-after-add","state":{"nums":[5,5],"k":0,"i":0,"seenSet":[5]}}]},"options":[{"id":"same-five","label":"That same 5, from index 0","rationale":"The value k positions back is at index 0 - 0, which is the 5 that just went in. The same happens to every value, so no lookup ever hits and k = 0 always returns false.","isCorrect":true},{"id":"none-yet","label":"None, because no earlier index exists","rationale":"Nothing leaves only when index i - k does not exist. Here it is index 0 - 0 = 0, which holds the 5.","isCorrect":false},{"id":"none-then-hit","label":"None, so the second 5 still matches it","rationale":"That would return true for indices 0 and 1, which are 1 apart. With k = 0 no two different indices are close enough.","isCorrect":false}]},{"id":"large-k-probe","kind":"case-probe","title":"In the second list, k is 10 and there are only four values. The 4 at index 3 arrives. What does the lookup find?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"large-k-arrive","state":{"nums":[4,1,2,4],"k":10,"i":3,"seenSet":[4,1,2]}}]},"options":[{"id":"hit","label":"The 4 from index 0, so it returns true","rationale":"Index 0 is 3 positions back and k is 10, so that pair counts. Index i - 10 never exists on this list, so nothing has left the set. The rule that removed the old 4 when k was 2 keeps it here.","isCorrect":true},{"id":"left","label":"No 4, because the first one has left","rationale":"A value leaves once the scan is k positions past it. With k = 10 that never happens on a list of four values.","isCorrect":false},{"id":"too-far","label":"A 4 that is too far back to count","rationale":"With k = 10 a gap of 3 is close enough. Every pair on this list is within reach.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"You have every step of the scan. Now write it.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["The function starts with an empty set and reads the list once, keeping track of each value's index.","For each value, it looks the value up in the set first. A hit means a copy sits at most k positions back, so the function returns true.","After a miss, it adds the value to the set. Then it removes the value k positions back, if the scan is that far along.","If the list ends without a hit, the function returns false."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-the-scan","state":{"nums":[4,1,2,4,2],"k":2,"seenSet":[]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Write the scan and its set","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"A set that holds only the last k values","workspacePanel":"code","takeaways":[{"title":"Only the last k values can match","body":"An earlier copy only counts for the value at index i if it sits at most k positions back, so the set holds the values from those indices and nothing older."},{"title":"Look up first, then add and remove after a miss","body":"Looking up before adding keeps a value from matching itself. Removing the value at index i - k after that keeps a copy exactly k back in the set for its last lookup."},{"title":"O(n) time, O(min(n, k + 1)) space","body":"Each value costs one lookup, one add and at most one removal, so the scan takes O(n) time where looking back took up to n × k comparisons. The set never holds more than k + 1 values, which is O(min(n, k + 1)) space."}]}],"slidesOrigin":"authored"},"version":1}
