numbers = [2, 7, 11, 15], target = 9→ [0, 1]2 + 7 = 9, and the positions are different.
Given an array of integers and a target, return the indices of two different entries whose values add to the target. This lesson also returns an empty list when no pair exists. Return the earlier index first.
numbers = [2, 7, 11, 15], target = 9→ [0, 1]2 + 7 = 9, and the positions are different.
numbers = [3, 3], target = 6→ [0, 1]The two threes have equal values but different indices.
numbers = [1, 5, 9], target = 20→ []No two positions produce the target.
Compare every pair of different positions. This uses O(n²) time and O(1) extra space. It is easy to verify, but it repeats checks as the input grows.
Scan once from left to right. For a current value x, the only earlier value that can finish a pair is target − x. Look up that complement in a map before storing x. If it exists, return the saved index and the current index. Otherwise save x and continue.
Before examining index i, the map contains values from earlier indices only, each mapped to its earliest saved index. Therefore any map hit names a distinct prior position, and every pair ending at i can be found by exactly one complement lookup.
The map solution takes O(n) expected time with hash lookup and O(n) extra space. Worst-case hash behavior depends on the runtime. The pair comparison solution takes O(n²) time and O(1) extra space.
For [3, 3] with target 6, storing the current 3 before looking up its complement can return [0, 0]. Checking first and inserting second prevents that invalid self-pair.
The saved values below are the map before the current lookup. Try equal values and a target of twice that value.
Index 0 has value 2. Need 7.
Saved earlier: nothing yet
No earlier 7 yet. Save 2 at index 0, then continue.These choices help you inspect the reasoning. Your independent coding pass is measured separately.
Write solve(data). data.numbers is the integer array and data.target is the target. Return [earlierIndex, laterIndex], or [] when no pair exists. The built-in tests use pairs with a unique valid answer.
Opening the code studio…
Loading your saved attempts…
This lesson uses original explanations and examples. The external coding problem is available on LeetCode.