Two Sum Problem Classic Hash Solution in DSA Java - Time & Space Complexity
We want to understand how the time needed to find two numbers that add up to a target grows as the list gets bigger.
How does the number of steps change when the input list size increases?
Analyze the time complexity of the following code snippet.
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[0];
}
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: Single loop through the array.
- How many times: Exactly once for each element in the array.
- Inside the loop, checking and inserting in the hash map happens in constant time.
As the list gets bigger, the number of steps grows directly with the number of elements.
| 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 list.
[X] Wrong: "Since there is a loop inside a loop, the time is O(n²)."
[OK] Correct: There is only one loop; the hash map lookups are fast and do not add extra loops.
Understanding this solution shows you can use extra space to speed up searching, a common and useful skill in coding problems.
"What if the input array was already sorted and you used two pointers 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 CQuick Check:
Hash map = quick index lookup [OK]
- Thinking hash map sorts the array
- Storing sums instead of indices
- Using hash map to reverse elements
Solution
Step 1: Identify correct generic types for HashMap
Java uses wrapper classes Integer, not primitive int, for generics.Step 2: Check syntax correctness
HashMap map = new HashMap<>(); correctly declares HashMap with diamond operator for instantiation.Final Answer:
HashMap map = new HashMap<>(); -> Option DQuick Check:
Use wrapper classes and diamond operator [OK]
- Using primitive types int in generics
- Missing diamond operator <>
- Incorrect Map interface usage
public int[] twoSum(int[] nums, int target) {
Map map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[] {};
}Solution
Step 1: Trace the loop and map updates
i=0: map={}, complement=9-2=7, not found, map={2:0} i=1: complement=9-7=2, found in map at index 0, return [0,1]Step 2: Return indices of the two numbers that sum to target
Indices 0 and 1 correspond to numbers 2 and 7 which sum to 9.Final Answer:
[0, 1] -> Option BQuick Check:
2 + 7 = 9 [OK]
- Returning indices in wrong order
- Not checking complement before insertion
- Returning empty array incorrectly
public int[] twoSum(int[] nums, int target) {
Map map = new HashMap<>();
for (int i = 0; i <= nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[] {};
}Solution
Step 1: Identify the loop boundary error
The loop uses i <= nums.length which causes ArrayIndexOutOfBoundsException at last iteration.Step 2: Fix the loop condition
Changing to i < nums.length prevents out-of-bound access and fixes the error.Final Answer:
Change loop condition to i < nums.length -> Option AQuick Check:
Loop index must be less than array length [OK]
- Using <= instead of < in loop condition
- Changing map type unnecessarily
- Removing essential map insertion
public int[] twoSum(int[] nums, int target) {
Map map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[] {};
}Solution
Step 1: Trace the loop and map updates with duplicates
i=0: map={}, complement=6-3=3, not found, map={3:0} i=1: complement=6-3=3, found at index 0, return [0,1]Step 2: Understand handling of duplicates
Even with duplicates, the first pair found is indices 0 and 1, both 3s summing to 6.Final Answer:
[0, 1] -> Option AQuick Check:
3 + 3 = 6 [OK]
- Ignoring duplicates and returning wrong indices
- Returning empty array incorrectly
- Confusing indices with values
Ready to prove it?
Pass the test and this pattern moves unknown
