← Back to DSA Animator
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
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.