Two Sum Visualizer & Step-by-Step Algorithm Solution

Find indices of two numbers that add up to target using a single-pass hash map.

Category: arrays | Difficulty: Easy

Tags: Hash Map, Array, Complement

Two Sum

Explanation
Numbers Array
i
2
0
7
1
11
2
15
3
Lookup Map (Value → Index)
(Empty Map)
100%
state
target9
neededN/A
Initialization
1/10
Explanation

Starting twoSum function with target = 9.

Source Code
1function twoSum(nums, target) {
2 const map = new Map();
3 for (let i = 0; i < nums.length; i++) {
4 const complement = target - nums[i];
5 if (map.has(complement)) {
6 return [map.get(complement), i];
7 }
8 map.set(nums[i], i);
9 }
10 return [-1, -1];
11}