Part 1 walked the O(N²) brute force. This is the answer interviewers actually want.
One pass through the array. A hashmap of complements. O(N) time. Worth roughly 10⁴× more performance at the max constraint than the brute force.
But the real prize isn't the speed — it's the pattern. "Hashmap of complements" shows up across dozens of problems. Once you see it here, you'll start spotting it everywhere.
What's inside:
→ The insight: for every number x, what we really need is target − x (the COMPLEMENT)
→ Why a hashmap is the right structure (O(1) lookup, trade space for time)
→ The 4-step algorithm: walk → compute complement → check map → store
→ Algorithm trace on [2, 7, 11, 15] showing the seen-map fill up
→ The 9-line JavaScript solution, line by line
→ Complexity — O(N) time, O(N) space — and why that's a great interview trade
→ Why this never accidentally matches a number with itself (the ordering trick)
→ Three traps: order of lookup vs store, map direction, duplicate values
→ The pattern: also solves 4Sum II, Subarray Sum K, Pairs Divisible by 60
⏱ Chapters
00:06 Hook — from O(N²) to O(N)
00:22 Series map — Part 2 of 2
00:31 Problem refresher
00:42 Part 1 recap — what we beat
00:58 The insight — complement
01:16 Why a hashmap
01:30 The algorithm — 4 moves
01:55 Trace on [2, 7, 11, 15]
02:21 The 9-line JavaScript code
02:43 Complexity — O(N) time, O(N) space
03:01 Why no self-match — the ordering trick
03:20 Three traps that bite
03:53 The pattern — hashmap of complements
04:17 Subscribe + comment hook
Subscribe @Codebrainery — new Coding Problem decoded every week.
📚 Playlist: Coding Problems Decoded — One Pattern at a Time
📌 Topic: Coding Problems — Hashing & Frequency
#CodingProblems #TwoSum #Hashmap #CodingInterview #InterviewPrep #DataStructures #JavaScript #Codebrainery