Contains duplicate
- CH1 i
A set answers one question: has this number come up before?
Step through it →A hash map remembers what you've already read, so asking for a value, a partner or a group takes one lookup instead of a scan.
Each number is stored only after its own lookup, so seen never holds the current number or anything after it. A repeat overwrites its index, so a match pairs with the latest copy.
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
Storing 3 before its lookup finds it at once and answers [0, 0]. Looking up first finds 2 + 4.
A set answers one question: has this number come up before?
Step through it →Count up for one string and down for the other. Anagrams end at all zeros.
Step through it →Key each word by its letter counts, and the groups form on their own.
Step through it →Walk a run only from its first number, the one whose left neighbor is missing.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
def two_sum(nums, target): seen = {} for i, num in enumerate(nums): complement = target - num if complement in seen: return [seen[complement], i] seen[num] = i return []