Two Sum: The Most Important First Problem
Two Sum (#1) is the most solved problem on LeetCode — and for good reason. With over 15 million submissions, it is the canonical entry point for anyone preparing for coding interviews. But Two Sum is not just a warm-up exercise. It teaches the single most important pattern in all of technical interviews: the hash map lookup.
The beauty of Two Sum is that it has a deceptively simple brute force solution that anyone can write, and an elegant optimal solution that requires a genuine insight. That gap between brute force and optimal is exactly what interviewers want to see you navigate.
In this walkthrough, you will understand the problem completely, implement both approaches, learn why the hash map solution works, and see how this pattern extends to dozens of other problems. Whether you are just starting your two sum leetcode journey or reviewing before an interview, this guide covers everything you need.
Understanding the Two Sum Problem
The problem statement is straightforward. Given an array of integers nums and an integer target, return the indices of the two numbers that add up to the target. You may assume that each input has exactly one solution, and you may not use the same element twice.
For example, given nums = [2, 7, 11, 15] and target = 9, the answer is [0, 1] because nums[0] + nums[1] equals 2 + 7 which equals 9. The constraint that exactly one solution exists simplifies the problem — you do not need to handle cases with no solution or multiple solutions.
What makes this leetcode two sum solution interesting is not the problem itself but the leap from the obvious approach to the optimal one. The brute force checks every possible pair. The optimal approach reframes the question entirely.
- Input: an integer array nums and an integer target
- Output: indices of two numbers that sum to target
- Constraint: exactly one valid solution exists
- Constraint: you cannot use the same element twice
- Return the indices (not the values themselves)
Did You Know?
Two Sum is the most solved problem on LeetCode with over 15 million submissions — it is the canonical introduction to the hash map pattern and the first problem most engineers ever solve.
Approach 1: Brute Force Two Sum
The brute force approach is the first thing most people think of. Use two nested loops to check every possible pair of numbers. For each element at index i, iterate through every element at index j where j > i, and check whether nums[i] + nums[j] equals the target.
This works correctly and is easy to implement. In Python it looks like: for i in range(len(nums)), for j in range(i+1, len(nums)), if nums[i] + nums[j] == target, return [i, j]. The logic is crystal clear.
The problem is performance. With two nested loops, the time complexity is O(n^2). For an array of 10,000 elements, that is up to 50 million comparisons. It passes on LeetCode because the constraints allow it, but in an interview, the follow-up is always: can you do better?
Space complexity is O(1) since you only use loop variables. This is the one advantage brute force has over the optimal approach — it uses no extra memory.
- Time complexity: O(n^2) — check every pair with nested loops
- Space complexity: O(1) — no additional data structures
- Pros: simple to write, easy to understand, no extra memory
- Cons: slow for large inputs, not what interviewers want to see as your final answer
Approach 2: Hash Map — The Optimal Two Sum Solution
The optimal two sum hash map approach flips the problem on its head. Instead of searching for a pair, you search for a complement. For each number you encounter, you ask: have I already seen the number that would complete this pair?
Here is the algorithm. Create an empty hash map. Iterate through the array once. For each element nums[i], compute complement = target - nums[i]. If the complement exists in the hash map, you have found your pair — return [hashmap[complement], i]. Otherwise, store nums[i] with its index in the hash map and move on.
In Python: seen = {}, for i, num in enumerate(nums), complement = target - num, if complement in seen, return [seen[complement], i], seen[num] = i. That is the entire solution in five lines.
This runs in O(n) time because you traverse the array once, and each hash map lookup is O(1) on average. Space complexity is O(n) because in the worst case you store every element before finding the pair. This is the classic time-space trade-off that interviewers love to discuss.
- Time complexity: O(n) — single pass through the array
- Space complexity: O(n) — hash map stores up to n elements
- One-pass solution: you check and insert in the same loop
- The hash map maps each value to its index for instant complement lookup
Key Insight
The key insight in Two Sum isn't the hash map itself — it's recognizing that 'find two numbers that sum to X' is equivalent to 'for each number, check if X minus that number exists'. This complement-search pattern appears in dozens of problems.
Why the Hash Map Approach Works
The key insight in Two Sum is a reframing. The brute force asks: which two numbers add up to the target? The hash map approach asks: for this number, does its complement already exist? By converting a search problem into a lookup problem, you eliminate the inner loop entirely.
Think of it this way. The brute force scans the entire array for each element. The hash map remembers every element it has seen, so when it encounters a new element, it can instantly check whether the missing piece exists. Memory replaces repeated computation.
This complement-search pattern is not unique to Two Sum. It appears whenever you need to find pairs, triples, or groups that satisfy a condition. Two sum explained at this level becomes a gateway to understanding hash-map-driven solutions across LeetCode. Problems like 3Sum, 4Sum, subarray sum equals K, and longest substring without repeating characters all use variations of this lookup-instead-of-search idea.
Understanding why this works — not just how to code it — is what separates candidates who solve one problem from those who recognize the pattern in twenty problems.
Edge Cases and Follow-Up Problems
Even though Two Sum guarantees exactly one solution, interviewers often ask about edge cases to test your thoroughness. What if the array contains duplicate values? The hash map handles this naturally because you check for the complement before inserting the current value. If nums = [3, 3] and target = 6, the first 3 goes into the map, and when you reach the second 3, complement = 3 is already in the map.
What about negative numbers? No special handling needed. The complement formula target - nums[i] works for negative values just as well. What about zero? Same thing — no edge case at all. The algorithm is robust by design.
The most common follow-up is Two Sum II (#167), where the array is sorted. Since it is sorted, you can use two pointers instead of a hash map — start one pointer at the beginning and one at the end, then move them inward based on whether the current sum is too large or too small. This achieves O(n) time with O(1) space.
The next extension is 3Sum (#15), which asks for three numbers that sum to zero. The standard approach sorts the array, fixes one element, and uses two pointers for the remaining pair. Recognizing that 3Sum builds directly on Two Sum is exactly the kind of pattern recognition that interviewers reward.
- Duplicate values: handled naturally since you check before inserting
- Negative numbers and zero: no special handling required
- Two Sum II (#167): sorted input allows O(1) space two-pointer solution
- 3Sum (#15): fix one element, run Two Sum on the rest with two pointers
- 4Sum (#18): same idea extended one more level
Interview Tip
Interviewers who ask Two Sum aren't testing if you can solve it — they're testing if you can explain the brute force, optimize to O(n), and discuss trade-offs. Don't just jump to the answer.
What Two Sum Teaches You About Interview Patterns
Two Sum is not just a problem — it is a lesson in algorithmic thinking. The jump from brute force to optimal teaches you the most common optimization technique in coding interviews: trade space for time using a hash map. This two sum brute force vs optimal comparison is something you will repeat in dozens of other problems.
The hash map lookup pattern — store what you have seen and check for what you need — appears in problems across every category. Anytime you catch yourself writing nested loops to find a pair or a complement, pause and ask: can I use a hash map to eliminate the inner loop?
Here is a partial list of problems that use the same core idea: Two Sum (#1), Two Sum II (#167), 3Sum (#15), Group Anagrams (#49), Valid Anagram (#242), Contains Duplicate (#217), Subarray Sum Equals K (#560), and Longest Consecutive Sequence (#128). Mastering Two Sum means you already understand the foundation for all of these.
Practice this pattern until the complement-search idea is automatic. YeetCode flashcards are designed to drill exactly this kind of pattern recognition — not memorizing solutions, but recognizing when a problem maps to a known technique. Once Two Sum clicks, the hash map pattern will be one of your most reliable tools in any interview.