Two Sum Problem Classic Hash Solution in DSA C - Time & Space Complexity
We want to know how the time needed to find two numbers that add up to a target grows as the list gets bigger.
How does the solution's speed change when the input size increases?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
#include <stdlib.h>
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int* map = (int*)calloc(2048, sizeof(int));
int* result = (int*)malloc(2 * sizeof(int));
for (int i = 0; i < numsSize; i++) {
int complement = target - nums[i];
if (map[complement & 2047]) {
result[0] = map[complement & 2047] - 1;
result[1] = i;
*returnSize = 2;
free(map);
return result;
}
map[nums[i] & 2047] = i + 1;
}
*returnSize = 0;
free(map);
return NULL;
}
This code finds two numbers in an array that add up to a target using a simple hash map for quick lookups.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop through the array once.
- How many times: Exactly once for each element in the input array.
Each new number is checked and stored once, so the work grows steadily as the list grows.
| 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 number of operations grows directly with input size, doubling input roughly doubles work.
Time Complexity: O(n)
This means the time to find the two numbers grows in a straight line with the size of the input list.
[X] Wrong: "The hash map lookup inside the loop makes this solution slower than a simple double loop."
[OK] Correct: Hash map lookups are very fast and happen in constant time, so the overall time stays linear, unlike the double loop which grows much faster.
Understanding this solution's time complexity shows you can use smart data structures to speed up searching, a key skill in many coding challenges.
"What if we used a sorted array and binary search instead of a hash map? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of hash map in Two Sum
The hash map stores each number as a key and its index as the value for quick lookup.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 CQuick Check:
Hash map = quick lookup [OK]
- Thinking hash map sorts the array
- Assuming hash map stores all pairs
- Confusing hash map with array reversal
Solution
Step 1: Identify C++ STL syntax for hash map
In C++, unordered_map is used for hash maps with integer keys and values.Step 2: Check other options for correctness
int hashmap[1000]; is a fixed-size array, not a hash map. map hashmap = new map(); is invalid syntax. dict hashmap = {}; is Python syntax.Final Answer:
unordered_map hashmap; -> Option AQuick Check:
unordered_map = hash map in C++ [OK]
- Using array instead of hash map
- Confusing Python or Java syntax with C++
- Incorrect map declaration syntax
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
unordered_map map;
for (int i = 0; i < numsSize; i++) {
int complement = target - nums[i];
if (map.find(complement) != map.end()) {
int* result = (int*)malloc(2 * sizeof(int));
result[0] = map[complement];
result[1] = i;
*returnSize = 2;
return result;
}
map[nums[i]] = i;
}
*returnSize = 0;
return NULL;
}Solution
Step 1: Trace the loop and hash map insertions
At i=0, map = {2:0}. At i=1, complement = 9-7=2 found in map at index 0.Step 2: Return indices of complement and current number
Return [0,1] as the pair that sums to 9.Final Answer:
[0, 1] -> Option BQuick Check:
nums[0]+nums[1] = 2+7 = 9 [OK]
- Returning indices in wrong order
- Not checking complement before insertion
- Returning NULL when pair exists
for (int i = 0; i < numsSize; i++) {
map[nums[i]] = i;
int complement = target - nums[i];
if (map.find(complement) != map.end()) {
return {map[complement], i};
}
}Solution
Step 1: Analyze order of operations in loop
Current number is inserted before checking complement, causing false positive when complement equals current number.Step 2: Correct order to check complement before insertion
Check if complement exists in map first, then insert current number to avoid matching with itself.Final Answer:
Complement check should happen before inserting current number -> Option DQuick Check:
Check complement before insert [OK]
- Inserting before checking complement
- Wrong return syntax in C
- Starting loop from wrong index
Solution
Step 1: Trace the hash map insertions and complement checks
At i=0, map = {3:0}. At i=1, complement = 6-3=3 found at index 0.Step 2: Return indices of the first valid pair
Return [0,1] as the pair that sums to 6.Final Answer:
[0, 1] because nums[0] + nums[1] = 3 + 3 = 6 -> Option AQuick Check:
3 + 3 = 6 [OK]
- Ignoring duplicate values
- Returning wrong indices order
- Assuming no pair exists when duplicates present
Ready to prove it?
Pass the test and this pattern moves unknown
