Problem Statement
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Intuition
The brute-force approach checks every pair, but we can do better. As we iterate through the array, we can store each number's index in a hash map. For each new number, we check if its complement (target - current number) already exists in the map.
The key insight is that lookup in a hash map is , turning our nested loop into a single pass.
Approach
- Create an empty hash map to store values and their indices.
- Iterate through the array with index
i. - Compute
complement = target - nums[i]. - If the complement exists in the map, return
[map[complement], i]. - Otherwise, store
nums[i]: iin the map.
Solution
TypeScript
function twoSum(nums: number[], target: number): number[] {
const map = new Map<number, number>();
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);
}
throw new Error("No solution found");
}
Complexity Analysis
| Metric | Value | Explanation |
|---|---|---|
| Time | Single pass through the array | |
| Space | Hash map stores up to n elements |