💡
Exercise 10

Two Sum 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

This is THE most famous coding interview question — LeetCode #1: Two Sum. If you're going to master one problem, make it this one.

Given an array of integers nums and an integer target, return the indices of the two numbers that add up to the target.

Example:
nums = [2, 7, 11, 15], target = 9
[0, 1] because nums[0] + nums[1] = 2 + 7 = 9

Brute Force — O(n²): Try every pair.

# Brute force — slow! def twoSum(nums, target): for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: return [i, j]

Optimal — O(n) using HashMap:
The key insight: if we need a + b = target, then b = target - a. We can look up b in a hash map in O(1)!

💭 Challenge time! Now implement this yourself using the strategy above. The best way to learn is by doing! ⭐

How it works step by step:

  • i=0, num=2: complement=7, not in map → store {2: 0}
  • i=1, num=7: complement=2, 2 IS in map at index 0 → return [0, 1] ✓

Complexity: Time O(n), Space O(n)

📋 Instructions
Implement `twoSum(nums, target)` using the **hash map approach**. For each number, calculate the complement (target - num). Check if the complement exists in your hash map. If yes, return both indices. If no, store the current number and its index. Return the indices as a list `[i, j]` where `i < j`.
Use a dictionary: hashmap = {}. For each number, calculate complement = target - num. If complement is in hashmap → return both indices. Otherwise, store num: index.
⚠️ Try solving it yourself first — you'll learn more!
def twoSum(nums, target):
    hashmap = {}  # value → index
    for i, num in enumerate(nums):
        complement = target - num
        if complement in hashmap:
            return [hashmap[complement], i]
        hashmap[num] = i
🧪 Test Cases
Input
twoSum([2, 7, 11, 15], 9)
Expected
[0, 1]
Test case 1
Input
twoSum([3, 2, 4], 6)
Expected
[1, 2]
Test case 2
Input
twoSum([3, 3], 6)
Expected
[0, 1]
Test case 3
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.