Two Sum
EasyArrays · HashingO(n) time · O(n) space
The problem
Given an array of integers and a target, return the indices of the two numbers that add up to the target. Exactly one answer exists and you may not use the same element twice.
nums = [2, 7, 11, 15], target = 9 → [0, 1]
nums = [3, 2, 4], target = 6 → [1, 2]Stuck? Open one hint
While you walk the array, what would you need to have remembered to answer in one step at the current element?
Show the worked solution
The brute force is two loops — O(n²). The interviewer is waiting for you to notice that for the current number x, you are looking for exactly one value: target - x.
So keep a map of value → index of everything you have already passed. At each element, check whether its complement is already in the map. One pass, one lookup per element.
Say this out loud: "I am trading space for time — a hash map turns the inner loop into an O(1) lookup."
fun twoSum(nums: IntArray, target: Int): IntArray {
val seen = HashMap<Int, Int>() // value -> index
for (i in nums.indices) {
val need = target - nums[i]
seen[need]?.let { return intArrayOf(it, i) }
seen[nums[i]] = i
}
return intArrayOf()
}O(n) time · O(n) space
