Data Structures & Algorithms Hash Maps & Sets
💡
Exercise 29

Two Sum (HashMap) 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Remember the Two Sum problem from the Arrays chapter? We solved it with nested loops in O(n²). Now let's crush it in O(n) using a hash map!

The insight: for each number, calculate its complement (target - num). If the complement is already in our hash map, we found our pair!

💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀

This is the classic example of trading space for time — we use O(n) extra space to get O(n) time instead of O(n²).

📋 Instructions
Implement `two_sum(nums, target)` using a hash map approach. Given `nums = [2, 7, 11, 15]` and `target = 9`, print the indices of the two numbers that add up to target. Expected output: `[0, 1]`
Iterate through nums. For each number, check if (target - num) exists in your dictionary. If yes, return both indices. Otherwise, store num: index.
⚠️ Try solving it yourself first — you'll learn more!
def two_sum(nums, target):
    seen = {}  # value → index
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
🧪 Test Cases
Input
two_sum([2, 7, 11, 15], 9)
Expected
[0, 1]
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.