An interactive visualization of the hash map approach to Two Sum. Watch how a single pass through the array with O(1) lookups finds the pair that sums to the target.
Hash Map LeetCode 1 ↗ Easynums and an integer target, return
indices of the two numbers such that they add up to target.fun twoSum(nums: IntArray, target: Int): IntArray { val seen = hashMapOf<Int, Int>() for ((i, num) in nums.withIndex()) { val complement = target - num if (complement in seen) return intArrayOf(seen[complement]!!, i) seen[num] = i } return intArrayOf() // no solution}
Instead of checking every pair with a nested loop (O(n²)), we trade O(n) space for O(1) lookup time. As we iterate, we store each number we have seen in a hash map. For the current number, we only need to check whether its complement (target − num) has already been seen — a single O(1) hash map lookup.
seen mapping number → index.nums[i], compute complement = target - nums[i].[seen[complement], i]. Done!seen[nums[i]] = i and continue.
We iterate through the array once (n elements), and each hash map operation (lookup and insert) is O(1) on average.
The hash map stores at most n entries, so space is O(n).