š¶Explain Like I'm 5
š§© Real-Life Example: Finding Your Lost Sock's Match
Imagine you have a pile of random socks (unsorted!). You want to find two socks whose sizes add up to exactly 10.
ā Slow Way (Brute Force - O(n²)):
Pick sock #1, compare with ALL other socks. Pick sock #2, compare with ALL other socks. Takes FOREVER!
If you have 100 socks, you make 10,000 comparisons! š°
ā Smart Way (HashMap - O(n)):
- Pick up sock with size 3. You need a sock of size 7 (10 - 3 = 7).
- Check your "memory book" (HashMap): "Have I seen size 7?"
- If YES ā Found it! š
- If NO ā Write down "I saw size 3 at position 0" and move to next sock.
You only touch each sock ONCE! Way faster! ā”
š” Key Insight: complement = target - current
We don't search for pairs. We search for the ONE number that completes the current number!
ā” Why HashMap is Magic: Looking up a value in HashMap takes O(1) time - instant! Like having a super-fast index in a book!
š Code Debugger
š Variables:
šÆ Array & HashMap
Array:
HashMap (seen numbers):
Empty - building as we go...
Click "Start" to begin visualization
ā Complete Java Solution
HashMap Patternpublic int[] twoSum(int[] nums, int target) {
HashMap<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); // Store value ā index
}
return new int[]{-1, -1}; // Not found
}
// Time Complexity: O(n) - single pass
// Space Complexity: O(n) - HashMap storageā” Why HashMap? Time Complexity Battle!
ā Brute Force (Two Nested Loops):
Time: O(n²) š
For n=10,000 elements, that's 100 million comparisons!
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (arr[i] + arr[j] == target)
return new int[]{i, j};
}
}ā HashMap Solution (One Pass):
Time: O(n) ā”
For n=10,000 elements, only 10,000 operations!
for (int i = 0; i < n; i++) {
if (map.containsKey(complement))
return new int[]{map.get(...), i};
map.put(nums[i], i);
}š” HashMap lookup/insert is O(1) - constant time!
That's why HashMap is 10,000x faster for large arrays! š