Apply hash-map lookups to solve Two Sum and verify the implementation with test cases.
Use the editor below to find two array positions whose values add up to the target.
Scan from left to right
Think about what information to remember as you scan. Handle duplicate values, negative numbers, and pairs far apart in the array.
Submit your implementation when it passes the examples.
Given an array of integers nums and an integer target, return the indices of the two different elements whose values add up to target.
Exactly one valid answer exists. Return the two indices in increasing order.
2 ≤ nums.length ≤ 10,000Results appear here after a run.
Store each value's index as you scan the array. Before storing the current value, calculate the complement needed to reach the target and check whether that complement has already appeared.
Checking first prevents the same element from being used twice. In the figure the two values are 2 and 7. Return their zero-based indices, [0, 1], in increasing order.
function twoSum(nums, target) {
const indexByValue = new Map();
for (let index = 0; index < nums.length; index++) {
const complement = target - nums[index];
if (indexByValue.has(complement)) {
return [indexByValue.get(complement), index];
}
indexByValue.set(nums[index], index);
}
return [];
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | Average O(n) | The array is scanned once, with average constant-time map lookups. |
| Auxiliary space | O(n) | The map may store an index for every visited value. |