Lesson 17: Heaps, Hash Maps and Two Pointers
Some problems are not about a clever algorithm at all — they are about having the right tool ready. Three tools come up so often in contests that they deserve a lesson of their own. The first is the heap, Python's heapq module: a list kept in heap order, where the smallest item is always at position 0, and pushing or popping costs O(log n). Heaps answer questions like "what are the three largest values?" or "process tasks in order of priority" without sorting the whole collection every time.
The second tool is the hash map — a Python dictionary — used as a counting or lookup table. A huge number of contest problems reduce to "have I seen this before, and how often?" Two-sum is the classic example: for each number, check whether its complement (target minus the number) is already in the dictionary; if it is, you have found a pair. That turns an O(n^2) search over all pairs into a single O(n) pass. Whenever a problem asks about pairs, frequencies or duplicates, reach for a dictionary first.
import heapq
def two_sum(nums, target):
seen = {} # value -> index
for i, x in enumerate(nums):
need = target - x
if need in seen:
return (seen[need], i)
seen[x] = i
return None
print(two_sum([2, 7, 11, 15], 9)) # (0, 1) — 2 + 7 = 9
# Three largest values, without sorting the whole list:
print(heapq.nlargest(3, [5, 1, 9, 3, 7])) # [9, 7, 5]
Two pointers: one pass, two positions
The third tool is the two-pointer technique: keep two indices into a sorted list (or a string) and move them toward each other, or together, according to what you find. To check whether a sorted list contains a pair summing to a target, put one pointer at the start and one at the end: if the sum is too small, move the left pointer right; if too large, move the right pointer left. Each step discards one value, so the whole check is O(n) after sorting. Two pointers also solve palindrome checks, removing duplicates from a sorted list, and merging two sorted lists — the same merge step you met in merge sort.
What unites these three tools is a habit of mind: before writing a nested loop, ask whether a better structure or a smarter scan exists. A dictionary turns a search into a lookup. A heap turns a repeated "find the smallest" into a cheap pop. Two pointers turn a pair search into a single pass. None of them is hard to learn, and together they solve a remarkable fraction of contest problems — which is why experienced competitors reach for them without thinking.
Going further
Python's heapq is a min-heap: the smallest item is always on top. To get a max-heap — the largest item first — the usual trick is to store negated values, pushing -x instead of x, so the smallest negated value corresponds to the largest original. It is a small hack, but it is the standard one, and it appears in countless contest solutions. A related trick is to store tuples such as (priority, item) in the heap, so the heap orders by priority and you can attach any data you like to each entry.
Two pointers also appear in a different guise: the fast and slow pointer technique on linked lists. One pointer advances one step at a time and the other two steps; if there is a cycle, the fast pointer eventually laps the slow one, and if there is not, the fast pointer reaches the end. The same pair of pointers finds the middle of a list in a single pass. The idea is the same as the sorted-list version — two positions moving at different rates, revealing structure that a single scan would miss — and it is worth recognising as one technique with many faces.
The two-sum pattern generalises further than it first appears. The same dictionary scan solves the problem of finding two numbers whose difference is a target, or two words that are anagrams of each other, or the first repeated character in a string. In each case the trick is the same: as you scan, you ask the dictionary a question about the past — have I seen the complement, have I seen this word's sorted form, have I seen this character before — and the dictionary answers in constant time. Whenever a problem asks about pairs, or about something seen before, the dictionary is the first tool to reach for.
Key Terms
- Heap
- A structure (Python's heapq) keeping the smallest item on top, with O(log n) push and pop.
- heapq
- The standard-library module providing heap operations on a plain list.
- Hash map (dictionary)
- A key-to-value store with O(1) average lookup, used for counting and remembering what has been seen.
- Two pointers
- A technique using two indices moving through a list or string, usually in a single O(n) pass.
- Complement
- In two-sum, the value needed to complete the pair: target minus the current number.
- nlargest / nsmallest
- heapq helpers returning the n largest (or smallest) items without a full sort.
- Single pass
- An algorithm that reads the input once, in O(n) time, keeping only what it needs.
Discussion Questions
- Why does two-sum with a dictionary run in O(n) while checking every pair is O(n²)? What does the dictionary remember that makes the difference?
- When would you use heapq.nlargest instead of sorting the whole list? What if you only need the single largest value?
- Two pointers needs a sorted list. Is it still worth sorting first? Compare the total cost with the O(n²) pair search.
Practice Questions
- Trace
two_sum([2, 7, 11, 15], 9). What is inseenwhen the answer is found? - What does
heapq.nlargest(3, [5, 1, 9, 3, 7])return? - Why is a heap better than sorting when you repeatedly need the smallest remaining item?
- Describe the two-pointer pair-sum check on a sorted list.
- A problem asks how many times each word appears in a text. Which tool, and why?
Show answers
- {2: 0}. After the first item, seen holds 2 at index 0; for x = 7, the complement 2 is already there, so it returns (0, 1).
- [9, 7, 5]. It returns the three largest values in descending order, without sorting the whole list.
- Each pop from a heap is O(log n); re-sorting after every removal would be O(n log n) each time. A heap keeps the minimum on top cheaply.
- Put one pointer at each end; if the sum is too small move left right, if too large move right left. Each step discards one value, so the check is a single O(n) pass.
- A dictionary (or Counter). One pass counts every word in O(n) with O(1) updates per word.