← DSA
EASY

Two Sum

PracticeNeetCode ↗LeetCode ↗

Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Each input has exactly one solution, and the same element can't be used twice.

Example

Input nums = [2,7,11,15], target = 9
Output [0,1]

Key Pointers

Step-by-Step Analysis

  1. Create an empty hashmap seen.
  2. For each index i, value n in nums: compute complement = target - n.
  3. If complement is already a key in seen, return [seen[complement], i].
  4. Otherwise store seen[n] = i and continue.

Complexity

Time: O(n) — Space: O(n)

Code

def twoSum(nums: list[int], target: int) -> list[int]:
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []

Code Explanation

How the solution above works, piece by piece.

  1. seen = {} maps each number already visited to its index.
  2. for i, n in enumerate(nums): one pass, with both index and value.
  3. complement = target - n: the partner this number needs.
  4. if complement in seen: the partner was visited earlier, so return both indices: the earlier one from the map and the current i.
  5. seen[n] = i: store the current number after the check, so a number can't pair with itself. One pass: O(n) time, O(n) space, instead of O(n²) for checking every pair.

Visual Walkthrough

Running it on nums = [2, 7, 11, 15], target = 9:

trace2071112153i=02→0need 7: not in map → store 2271115i=12→0need 2: in map at 0 → [0, 1]
At index 1 the value 7 needs 9 − 7 = 2, which is already in the map at index 0, so the answer is [0, 1] after only two steps.
current numbermatching partner

Video Explanation

Striver (takeUforward) — 2 Sum Problem, Brute-Better-Optimal