Hello! Let's dive into your next lesson on hashing.
In our last session, we saw how to apply hash maps to solve frequency counting problems like "Valid Anagram." The core pattern was mapping an element to its number of occurrences. This transformed problems that might seem to require expensive comparisons into simple, linear-time solutions.
Today, we'll tackle what is arguably the most famous and fundamental coding interview question: Two Sum. Your learning outcome is to solve the Two Sum problem and its variations using a hash-based approach. This lesson will solidify your understanding of how hash maps provide instant lookups and why this is a cornerstone pattern for your technical interview toolkit.
1. Understanding the Two Sum Problem
The problem is simple to state but serves as a perfect test for moving from a brute-force to an optimized mindset.
Problem Statement: Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.
- You may assume that each input would have exactly one solution.
- You may not use the same element twice.
Example:
- Input:
nums = [2, 7, 11, 15],target = 9 - Output:
[0, 1] - Explanation: Because
nums[0] + nums[1] == 9, we return[0, 1].
As with any interview problem, the first step is to think of a simple, correct solution, even if it's not the most efficient. This demonstrates a solid problem-solving foundation.
Two Sum - Leetcode 1 - HashMap - Python
The video "Two Sum - Leetcode 1" from the NeetCode channel provides an excellent introduction. It clearly explains the problem and the straightforward, but slow, brute-force approach.
Watch from the beginning to 01:49. Focus on understanding the nested loop logic of the brute-force solution and its O(n²) time complexity.
The brute-force approach, checking every possible pair of numbers, gives us a time complexity of . For a typical interview constraint where n can be up to 105, an algorithm would be too slow ( operations). This is your cue to find a more optimal solution.
2. The Hash Map Optimization
How can we do better? The bottleneck is finding the second number. For each element x in the array, we are looking for its complement, which is target - x. The brute-force method takes time to search for this complement.
What data structure gives us a faster search? The hash map, which provides an average lookup time of . This is the key insight.
The core idea is to trade space for time. We'll use a hash map to store the numbers we've already seen, allowing us to find the complement in an instant.
There are two main ways to structure this: a two-pass approach and a one-pass approach.
Two-Pass Hash Map Approach
This is an intuitive way to apply the hash map.
- First Pass: Iterate through the entire array and store each element and its index in a hash map. The map will look like
{value: index}. - Second Pass: Iterate through the array again. For each element
nums[i], calculate the complementc = target - nums[i]. Check ifcexists in the hash map. If it does, and its index is noti, you've found your solution.
1. Two Sum - Solution & Explanation
The article "1. Two Sum - Solution & Explanation" from NeetCode.io provides a clear, text-based explanation of this two-pass strategy.
Read the section "3. Hash Map (Two Pass)". Pay attention to the algorithm steps and the dry run, which clearly visualizes the two separate passes.
This approach is correct and improves the time complexity to , but can we do even better and solve it in a single pass?
One-Pass Hash Map Approach
This is the standard, most elegant solution you should aim for in an interview.
The logic is refined: you can build the hash map and check for the complement at the same time.
As you iterate through the array (let's say you're at index i with value x):
- Calculate the complement:
c = target - x. - Check if
calready exists in your hash map. If it does, you have found your pair! The first index is stored inmap[c], and the second index is your current index,i. - If the complement is not in the map, add the current value
xand its indexito the map. This prepares you for future iterations.
By checking for the complement before adding the current element, you naturally avoid using the same element twice.
Let's watch a video that walks through this clever one-pass trick.
Two Sum - Leetcode 1 - HashMap - Python
Let's return to the NeetCode video, which now explains the optimal one-pass solution. This is the key part of the lesson.
Watch from 01:49 to 05:28. The instructor does an excellent job explaining the logic of the one-pass approach and why checking for the complement before updating the map is so important.
Here is a visual representation of this one-pass process:

Test your understanding!
Consider the input nums = [3, 5, -4, 8, 11, 1, -1, 6] and target = 10.
Using the one-pass hash map approach, what is the state of the hash map right before the solution is found? What are the two numbers that form the solution?
Show answer
Let's trace the one-pass algorithm:
i=0,x=3,c=7.7not in map.map = {3: 0}.i=1,x=5,c=5.5not in map.map = {3: 0, 5: 1}.i=2,x=-4,c=14.14not in map.map = {3: 0, 5: 1, -4: 2}.i=3,x=8,c=2.2not in map.map = {3: 0, 5: 1, -4: 2, 8: 3}.i=4,x=11,c=-1.-1not in map.map = {3: 0, 5: 1, -4: 2, 8: 3, 11: 4}.i=5,x=1,c=9.9not in map.map = {3: 0, 5: 1, -4: 2, 8: 3, 11: 4, 1: 5}.i=6,x=-1,c=11.11is in the map! The algorithm finds the solution.
The state of the map right before finding the solution (at the start of iteration i=6) was:{3: 0, 5: 1, -4: 2, 8: 3, 11: 4, 1: 5}
The two numbers that form the solution are 11 (from the map) and -1 (the current number). Their indices are 4 and 6.
3. Implementation and Complexity
Now, let's translate this logic into code. Given your familiarity with Python, here is a clean implementation.
def two_sum(nums: list[int], target: int) -> list[int]:
seen = {} # A dictionary to store value -> index
for i, x in enumerate(nums):
complement = target - x
if complement in seen:
return [seen[complement], i]
seen[x] = i
return [] # Should not be reached based on problem constraints
This code perfectly implements the one-pass strategy.
- Time Complexity: . We traverse the list containing elements only once. Each lookup and insertion in the hash map takes time on average.
- Space Complexity: . In the worst case, we might have to store all elements in the hash map before finding the solution pair (e.g., if the pair is the last two elements).
This is a classic time-space tradeoff. We use extra memory to reduce the time complexity from quadratic to linear.
4. Variations and Interview Context
Recognizing and solving the basic Two Sum problem is just the first step. In an interview, you need to articulate your solution, discuss tradeoffs, and handle variations.
Two Sum LeetCode 1 Solution: Brute Force, Two Pointers, Hash Map
The article "Two Sum LeetCode 1 Solution" is a fantastic resource specifically for interview preparation. It not only provides code in multiple languages (including Python, Java, and C++) but also gives you the exact language to use in an interview.
This is a key resource for acing the interview. Please read the following sections carefully: "Pattern Recognition — How to Spot Two Sum in Interviews": Focus on the "Decision tree" and "Pattern mapping table". "Interview-ready explanation template": This provides a script for how to present your solution. "Edge Cases & Suggested Interview Demos": This shows you how to handle duplicates, zeros, and other edge cases, which demonstrates deep thinking.
One of the most common variations is when the input array is sorted.
- Question: If the input array
numswere sorted, could you solve this problem with space complexity? - Answer: Yes. You could use the Two Pointers technique. Start one pointer at the beginning (
left) and one at the end (right). Ifnums[left] + nums[right]is too small, incrementleft. If it's too large, decrementright. If it's equal to the target, you've found your pair. This takes time and space. We'll cover this pattern in-depth in a future module. Mentioning this alternative shows the interviewer that you think critically about problem constraints.
Conclusion
Congratulations! You've just mastered one of the most important patterns for technical interviews. The "find a complement using a hash map" strategy is applicable to a wide range of "pair-finding" problems.
Key Takeaways:
- The Two Sum Pattern: For a given element
x, you can instantly check for the existence of its complement (target - x) using a hash map. - One-Pass is Optimal: The one-pass hash map approach is the standard, efficient solution, achieving time and space.
- Articulate Tradeoffs: Be ready to discuss the brute-force solution and explain why the hash map's time-space tradeoff is superior. Also, be aware of constraint-specific alternatives like the two-pointer method for sorted arrays.
In the next lesson, we will look at Hash Sets. While hash maps store key-value pairs, hash sets are simpler: they only store unique keys. We will see how this is perfectly suited for problems involving duplicate detection and membership testing.