Two Sum Problem Classic Hash Solution in DSA C# - Time & Space Complexity
We want to understand how fast the Two Sum solution using a hash works as the input grows.
Specifically, how does the time to find two numbers that add up to a target change when the list gets bigger?
Analyze the time complexity of the following code snippet.
public int[] TwoSum(int[] nums, int target) {
var map = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++) {
int complement = target - nums[i];
if (map.ContainsKey(complement)) {
return new int[] { map[complement], i };
}
map[nums[i]] = i;
}
return new int[] { -1, -1 };
}
This code finds two numbers in the array that add up to the target using a hash map for quick lookups.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop over the array elements.
- How many times: Exactly once for each element, so n times if n is the array length.
- Inside the loop, hash map lookups and insertions happen in constant time on average.
Each element is checked once, and the hash map operations are very fast, so the total work grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and lookups |
| 100 | About 100 checks and lookups |
| 1000 | About 1000 checks and lookups |
Pattern observation: The work grows in a straight line as the input size grows.
Time Complexity: O(n)
This means the time to find the two numbers grows directly in proportion to the size of the input array.
[X] Wrong: "Because there is a loop inside a loop, the time is O(n²)."
[OK] Correct: There is only one loop, and the hash map lookups inside it happen very fast, not another full loop.
Understanding this solution's time complexity shows you can use data structures smartly to speed up problems.
This skill is useful in many coding challenges and real projects where speed matters.
"What if we used a simple nested loop instead of a hash map? How would the time complexity change?"
Practice
Two Sum Problem Classic Hash Solution?Solution
Step 1: Understand the role of hash map
The hash map stores numbers and their indices for quick lookup.Step 2: Use hash map to find complement
For each number, check if (target - number) exists in the map to find the pair.Final Answer:
To quickly check if the complement of the current number exists -> Option DQuick Check:
Hash map = fast complement check [OK]
- Thinking hash map sorts the array
- Trying to store sums instead of indices
- Ignoring the complement concept
Solution
Step 1: Identify correct dictionary declaration
In C#,Dictionary<int, int>is used for key-value pairs.Step 2: Check syntax correctness
Dictionary map = new Dictionary(); correctly declares and initializes the dictionary.Final Answer:
Dictionary map = new Dictionary(); -> Option AQuick Check:
C# dictionary syntax = Dictionary map = new Dictionary(); [OK]
- Using List instead of Dictionary
- Using Java's HashMap syntax in C#
- Not specifying generic types
[2, 7, 11, 15] and target 9?
public int[] TwoSum(int[] nums, int target) {
Dictionary map = new Dictionary();
for (int i = 0; i < nums.Length; i++) {
int complement = target - nums[i];
if (map.ContainsKey(complement)) {
return new int[] { map[complement], i };
}
map[nums[i]] = i;
}
return new int[] { -1, -1 };
}Solution
Step 1: Trace the loop and map updates
At i=0, map is empty; add (2,0). At i=1, complement=9-7=2 found in map at index 0.Step 2: Return indices of complement and current
Return [0,1] as the pair sums to 9.Final Answer:
[0, 1] -> Option BQuick Check:
nums[0]+nums[1] = 2+7 = 9 [OK]
- Returning indices in wrong order
- Not updating map correctly
- Returning [-1, -1] incorrectly
public int[] TwoSum(int[] nums, int target) {
Dictionary map = new Dictionary();
for (int i = 0; i <= nums.Length; i++) {
int complement = target - nums[i];
if (map.ContainsKey(complement)) {
return new int[] { map[complement], i };
}
map[nums[i]] = i;
}
return new int[] { -1, -1 };
}Solution
Step 1: Check loop boundary
The loop uses i <= nums.Length which causes index out of range error.Step 2: Correct loop condition
Change to i < nums.Length to avoid accessing invalid index.Final Answer:
Loop condition should be < instead of <= -> Option CQuick Check:
Loop boundary off by one causes error [OK]
- Using <= instead of < in loop
- Confusing data structures
- Ignoring index out of range exceptions
[3, 3, 4, 5] and target 6, what will the Two Sum hash solution return and why?Solution
Step 1: Trace the map and complements
At i=0, map empty, add (3,0). At i=1, complement=6-3=3 found at index 0.Step 2: Return indices of matching pair
Return [0,1] because nums[0]+nums[1]=3+3=6.Final Answer:
[0, 1] because the first two 3's sum to 6 -> Option AQuick Check:
Duplicate values handled correctly [OK]
- Ignoring duplicates in map
- Assuming no pair exists with same number twice
- Returning wrong indices
Ready to prove it?
Pass the test and this pattern moves unknown
