Overview
Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.
You may assume that each input has exactly one solution, and you may not use the same element twice. Return the indices in ascending order.
Implement twoSum(nums, target).
Constraints
2 ≤ nums.length ≤ 10000-1000000000 ≤ nums[i] ≤ 1000000000- Exactly one valid pair exists.
- Return indices sorted ascending:
[i, j]wherei < j. - Aim for $O(n)$ time using a hash map.
Examples
twoSum([2, 7, 11, 15], 9); // → [0, 1] — nums[0] + nums[1] = 2 + 7 = 9 twoSum([3, 2, 4], 6); // → [1, 2] — nums[1] + nums[2] = 2 + 4 = 6 twoSum([3, 3], 6); // → [0, 1]
Notes
- Use a hash map to store each number's index as you iterate. For each element, check if the complement (
target - nums[i]) exists in the map. - Single-pass $O(n)$ solution.
Solution
Reveal solution
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
}Resources
pair-sum.js
Pair Sum
easycodingAlgorithmsHash Map
Overview
Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.
You may assume that each input has exactly one solution, and you may not use the same element twice. Return the indices in ascending order.
Implement twoSum(nums, target).
Constraints
2 ≤ nums.length ≤ 10000-1000000000 ≤ nums[i] ≤ 1000000000- Exactly one valid pair exists.
- Return indices sorted ascending:
[i, j]wherei < j. - Aim for $O(n)$ time using a hash map.
Examples
twoSum([2, 7, 11, 15], 9); // → [0, 1] — nums[0] + nums[1] = 2 + 7 = 9 twoSum([3, 2, 4], 6); // → [1, 2] — nums[1] + nums[2] = 2 + 4 = 6 twoSum([3, 3], 6); // → [0, 1]
Notes
- Use a hash map to store each number's index as you iterate. For each element, check if the complement (
target - nums[i]) exists in the map. - Single-pass $O(n)$ solution.
Solution
Reveal solution
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
}Resources
NameTopicDifficulty
103 of 103 problems