#1
Easy
Two Pointers

Two Sum

Find two indices whose values add up to the target.

Given an array and a target, return the two indices whose values sum to the target. The key is preserving original indices while finding the complement in one pass.

ArrayHash Table

Pattern fit

Even though the best solution is hash-based, this problem teaches the interview habit of asking whether order or sorting could turn pair search into pointer movement.

Key observation

You are really solving a complement query: for each value x, ask whether target - x has appeared already.

Target complexity

O(n) / O(n)

How to break down the solution cleanly

1

Scan from left to right and treat each number as a complement query.

2

Before storing the current number, ask whether target - nums[i] has already appeared.

3

If it has, return the previous index and the current index immediately.

4

Otherwise store nums[i] -> i so later values can match against it.

Walk through one example

1

Example: nums = [2, 7, 11, 15], target = 9.

2

Read 2 first, store 2 -> 0 because 7 has not appeared yet.

3

Read 7 next, its complement 2 is already in the map, so answer is [0, 1].

Reference implementation

Python
def twoSum(nums, target):
    seen = {}

    for index, value in enumerate(nums):
        complement = target - value
        if complement in seen:
            return [seen[complement], index]
        seen[value] = index

    return []

Common pitfalls

warning

Forgetting that the answer needs original indices.

warning

Sorting blindly and losing the index mapping.

Common follow-ups

How would the solution change if the array were already sorted?

What if you needed all valid pairs instead of one pair?

Continue with related problems

Build repeatable depth inside the Two Pointers cluster before moving on.

view_weekBack to the pattern page
LeetCode 1. Two Sum Guide | Interview AiBox