Easy
Two Sum
👶 The 5-Year-Old Summary
You have a bunch of toys, and someone tells you "Find two toys that together cost exactly $9!" You look at each toy and think "If I have this one, what other one do I need?"
🎮 Interactive Visualizer
Click "Step" to watch how the algorithm finds the answer!
Hash Map (what we've seen):
🧠The Brain Hack
When a problem asks you to "find two numbers that add to X," think: "For each number, what do I need?" Use a hash map to remember what you've seen - it's like a cheat sheet!
💻 The Clean Solution
def two_sum(nums, target):
# A notebook to remember what we've seen
seen = {} # key: number, value: its index
# Go through each number one by one
for i, num in enumerate(nums):
# What number do we need to reach the target?
needed = target - num
# Have we seen that number before?
if needed in seen:
# Found it! Return the pair
return [seen[needed], i]
# Write this number in our notebook
seen[num] = i
# No solution found (shouldn't happen for valid input)
return []
# Try it!
nums = [2, 7, 11, 15]
target = 9
print(two_sum(nums, target)) # Output: [0, 1]
Time: O(n) - We only walk through the list once!
Space: O(n) - We use extra memory for the notebook.