DSA Visualizer · 25 visualizationsTwo Sum
EasyArrays & Hashing · Hash map

Two Sum

Find two indices whose values add up to the target. Instead of checking every pair, remember what you've already seen.

nums = [3, 8, 2, 11, 7, 15] · target = 9Step 1 of 6
3
0
8
1
2
2
11
3
7
4
15
5

Start with an empty hash map. It will remember every number we've passed and where we saw it.

Kotlintime O(n) · space O(n)
1fun twoSum(nums: IntArray, target: Int): IntArray {
2 val seen = HashMap<Int, Int>()
3 for (i in nums.indices) {
4 val need = target - nums[i]
5 if (need in seen) return intArrayOf(seen[need]!!, i)
6 seen[nums[i]] = i
7 }
8 return intArrayOf()
9}
Variables
i—
nums[i]—
need—
seen (hash map)value → index
empty
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough