Coding Interview: Patterns & DSA · Hashing & Sets · Lesson 2 of 2
The 'seen' set pattern
The seen pattern keeps a set (or map) of values encountered so far as you make a single pass, so you can detect duplicates or find complements in O(1). It converts many nested-loop searches into one linear scan.
Example: two-sum on an unsorted array
Unlike the sorted two-pointer version, an unsorted two-sum uses a map from value to index. For each number, check whether its complement (target - num) is already in the map; if so you are done in one pass.
def two_sum(nums, target): seen = {} # value -> index for i, num in enumerate(nums): need = target - num if need in seen: return [seen[need], i] # found the complement seen[num] = i return []
- Contains duplicate: add each element to a set; if it is already there, you found a repeat.
- First unique / first repeat: one pass to count, a second pass to find the target.
- Cycle / revisit detection: track visited nodes or states in a set.
Insert order mattersIn two-sum, check for the complement before inserting the current number, or an element can match itself. Order of check-then-insert is a common off-by-one bug.
◆ Lock it in
- The seen set records what you passed, enabling
O(1)duplicate/complement checks. - Unsorted two-sum: map value to index, look for
target - numin one pass. - Check the complement before inserting the current element.
Feynman drill — say it out loudWalk through why the hash-map two-sum is one pass and O(n), and where the self-match bug hides.
Step 1 rate your confidence · Step 2 pick your answer
In the one-pass hash-map two-sum, why check for the complement before inserting the current number?
Step 1 — how sure are you?