DSA AnimatorDSA animations
Two Sum LC #1 Easy HashMap
Problem

Given an array of integers nums and an integer target, return indices of the two numbers that add up to target. You may assume exactly one solution exists, and you may not use the same element twice.

Example 1
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9.
Constraints: 2 ≤ nums.length ≤ 10⁴  |  −10⁹ ≤ nums[i] ≤ 10⁹  |  Exactly one valid answer
Try Examples
Custom:
Approach
HashMap — One Pass
For each element, check if its complement (target - nums[i]) is already stored in the map. If found, return both indices immediately. Otherwise, store the current value and index. One pass, O(n).
Arrays & HashMap
Value (Key)Index (Value)
Variables
i (index)
—
nums[i]
—
complement
—
result
—
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Initialize empty HashMap (value → index)
2
For each i: compute complement = target − nums[i]
3
If map has complement → return [map.get(complement), i]
4
Else: put nums[i] → i in map, continue
Time
O(n)
Space
O(n)
Why It Works

A HashMap gives O(1) average-case lookup. For every element we check whether its complement already exists — meaning we've previously seen the other number that would complete the sum. If found, we immediately have both indices. If not, we record the current number for future lookups. This single pass eliminates the need for a brute-force O(n²) nested loop.

How to solve Two Sum

LeetCode 1 · Easy · Arrays · Pattern: Hash Map

Why the obvious approach is slow

Checking every pair works, but it is O(n²). For a big array, that is far too slow.

The key idea

For each number, ask: have I already seen the number I need? The number you need is the target minus the current number. A hash map from value to index answers that in constant time.

Remember

Two Sum means storing what you have seen in a hash map. For each number, look up target minus the number.

Run the animation above on your own input, or watch the 1:12 video explanation of Two Sum with a dry run and Java code.

More Arrays problems