All Blind 75 questions

Two Sum

FreeArrays & hashingEasy1 of 75

The problem

Find the indices of two different elements of an integer array whose sum equals a target. Assume exactly one pair exists; return the indices in either order.

Example

nums = [4, 1, 9, 7], target = 10 → [1, 2]

Need a hint?

What information would let you find the partner of the current value immediately?

Write pseudocode, trace the example, or note an edge case. This scratchpad does not run code.

Notes stay in this browser when storage is available.

Read the solution approach

Scan left to right while mapping previously seen values to their indices. Before inserting x, look for target − x. Checking before insertion prevents using the same element twice. Return the saved index and the current index on a match.

Complexity

O(n) expected time and O(n) space with a hash map.

Before moving on, explain why the algorithm is correct and trace a boundary case without looking at the approach.