CodingEasy Arrays & Hashing
Two Sum
Asked for all developer roles
Why they ask this: The most common warm-up problem; it checks whether you can trade memory for speed with a hash map.
Problem
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Assume exactly one solution exists, and you may not use the same element twice.
Example 1
text
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1] // nums[0] + nums[1] = 2 + 7 = 9Example 2
text
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]Hints
Approach
Brute force compares every pair: O(n²) time.
Optimal (one pass with a hash map): walk through the array once. For each nums[i], compute need = target - nums[i].
- If
needis already in the map, return[map[need], i]. - Otherwise store
nums[i] → iin the map.
Checking before inserting stops an element from pairing with itself.
Solution
js
function twoSum(nums, target) {
const seen = new Map(); // value -> index
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) {
return [seen.get(need), i];
}
seen.set(nums[i], i);
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1] Time
O(n) Space O(n)Can you explain this in your own words?