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
08
12
211
37
415
5Start 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
emptyNext upValid Parentheses
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough