Two Sum Problem Classic Hash Solution in DSA Javascript - Time & Space Complexity
We want to understand how fast the classic hash solution for the Two Sum problem runs as the input size grows.
Specifically, how does the number of steps change when the list of numbers gets bigger?
Analyze the time complexity of the following code snippet.
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);
}
return [];
}
This code finds two numbers in the array that add up to the target using a hash map for quick lookups.
- Primary operation: One loop that goes through each number once.
- How many times: Exactly once for each number in the input array.
- Inside the loop, checking and adding to the map are quick, constant-time operations.
As the list gets bigger, the number of steps grows directly with the number of numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and inserts |
| 100 | About 100 checks and inserts |
| 1000 | About 1000 checks and inserts |
Pattern observation: The steps increase evenly as the input size increases.
Time Complexity: O(n)
This means the time to find the two numbers grows in a straight line with the size of the input.
[X] Wrong: "Because there is a loop inside a loop, the time is O(n²)."
[OK] Correct: There is only one loop here; the map lookups are very fast and do not add extra loops.
Understanding this solution's time complexity helps you explain why using a hash map is efficient and preferred in interviews.
"What if we used a nested loop to check every pair instead of a hash map? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of hash map
The hash map stores each number as a key and its index as the value for quick access.Step 2: Explain why quick lookup is needed
Quick lookup helps find if the complement (target - current number) exists without scanning the entire array again.Final Answer:
To store numbers and their indices for quick lookup -> Option AQuick Check:
Hash map = quick index lookup [OK]
- Thinking hash map sorts the array
- Storing sums instead of indices
- Using hash map to reverse array
Solution
Step 1: Recall JavaScript Map method for key check
The correct method to check if a key exists in a Map ishas().Step 2: Verify other options are invalid
Methodscontains(),exists(), andincludes()do not exist on Map objects.Final Answer:
map.has(key) -> Option AQuick Check:
Map key check = has() [OK]
- Using contains() instead of has()
- Using includes() which is for arrays
- Trying to access keys directly
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);
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9));Solution
Step 1: Trace the loop and map updates
At i=0, map is empty, store (2,0). At i=1, complement=9-7=2, map has 2 at index 0.Step 2: Return indices when complement found
Return [0,1] as indices of numbers 2 and 7 that sum to 9.Final Answer:
[0, 1] -> Option CQuick Check:
Indices of 2 and 7 = [0, 1] [OK]
- Returning values instead of indices
- Not updating map before checking complement
- Returning empty array incorrectly
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);
}
return [];
}Solution
Step 1: Check loop boundary
The loop uses i <= nums.length which causes out-of-bounds access at last iteration.Step 2: Correct loop condition
Change to i < nums.length to avoid accessing undefined element.Final Answer:
Loop condition should be i < nums.length, not i <= nums.length -> Option DQuick Check:
Loop boundary off-by-one error [OK]
- Using <= instead of < in loop
- Swapping map.set and complement check order
- Returning values instead of indices
nums = [3, 3, 4, 5] and target 6, what will the Two Sum classic hash solution return?
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);
}
return [];
}Solution
Step 1: Trace the loop with duplicates
At i=0, map empty, store (3,0). At i=1, complement=6-3=3, map has 3 at index 0.Step 2: Return indices of first matching pair
Return [0,1] because nums[0] + nums[1] = 3 + 3 = 6.Final Answer:
[0, 1] -> Option BQuick Check:
Duplicates handled, first pair indices returned [OK]
- Returning later pair indices instead of first
- Ignoring duplicates in map
- Returning values instead of indices
Ready to prove it?
Pass the test and this pattern moves unknown
