The Problem

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Interactive Visualization

Speed:
Array
Hash Map (seen)
Empty — entries will appear as the algorithm runs
Current Step
Press Step or Play to begin.
Code
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}

How It Works

Key Insight

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.

The Algorithm

  • Initialize an empty hash map seen mapping number → index.
  • For each element nums[i], compute complement = target - nums[i].
  • Look up the complement in the hash map:
  • — If found: return [seen[complement], i]. Done!
  • — If not found: store seen[nums[i]] = i and continue.
  • Since exactly one solution exists, the algorithm always finds it in a single pass.

Complexity

Time O(n)
Space O(n)

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).