LeetEye LeetEye
Easy Hash Set / Hash Map ~5 min

Two Sum

arrays-and-hashing two-sum

Problem

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

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Examples

Example 1
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
nums[0] + nums[1] = 2 + 7 = 9
Example 2
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
nums[1] + nums[2] = 2 + 4 = 6
Example 3
Input: nums = [3, 3], target = 6
Output: [0, 1]
Key Insight

You're not searching for "any pair." You're searching for a specific value.

For pair problems, don't search for pairs. Calculate the complement and look it up.

How to Approach This Problem

Pattern Recognition: When you see keywords like two sum arrays-and-hashing, think Hash Set / Hash Map.

Step-by-Step Reasoning

1 If the target is 9 and the current number is 4, what specific value are you looking for?
Answer: The number 5
If current = 4 and target = 9, the complement is 9 - 4 = 5. We're not looking for "some number" - we're looking for exactly 5.
2 For each number in the array, the main operation is:
Answer: Check if its complement exists in what we've seen
The key operation is complement lookup. "Does (target - current) exist in our collection?"
3 Why is a hash map better than an array for storing seen numbers?
Answer: Hash map gives O(1) lookup by value
We need to look up "does value X exist?" - this requires searching by value. Arrays give O(1) lookup by index, but O(n) lookup by value. Hash maps give O(1) lookup by key (the value itself).
4 The hash map should store:
Answer: value → index
We search BY value (the complement) and we need to RETURN the index. So: key = value, stored data = index.
5 For each number, which order is correct?
Answer: Check for complement, then add to map
Check first, add second. If you add first, you might match a number with itself (when complement == current and they're the same element).
6 Given nums = [3, 3], target = 6. Why does checking before adding work?
Answer: First 3 is added, second 3 finds complement
Process first 3: check for 3 (not found), add 3→0. Process second 3: check for 3 (found at index 0!), return [0, 1]. The order ensures we don't match an element with itself.

Solution

def twoSum(nums: List[int], target: int) -> List[int]:
    seen = {}  # value -> index
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

Complexity Analysis

Time O(n)
Space O(n)

Master This Pattern

Build intuition with interactive MCQs. Practice Hash Set / Hash Map problems in the LeetEye app.

Download LeetEye Free
Practice in LeetEye