π― Coding Interview Patterns
in Python
Learn the coding interview patterns in Python: two pointers, sliding window, hash maps, stacks, binary search on the answer, backtracking and heaps, with complexity.
What this lesson is about
Coding interview problems look endless, but most of them are small variations of a short list of patterns. Two pointers, sliding window, hash maps, stacks, binary search, backtracking and heaps cover a surprisingly large share of the questions on platforms such as LeetCode and in technical screens. These patterns are also ordinary working tools: deduplicating sorted data, finding the best window in a log, grouping records or picking the top results all use them.
The goal of this lesson is not to memorise solutions. It is to train recognition: given a new problem, you should be able to say 'this smells like a sliding window because I need the best contiguous range and the window can grow and shrink', and then know the template, the complexity and the traps. For each pattern I show the signals that point to it, a small runnable solution with printed steps, and the time and space cost.
The page goes through the patterns in the order I find easiest to learn them, then finishes with a recognition table and a testing habit that I recommend for any practice session. You should be comfortable with lists and dictionaries first. Complexity is discussed in Big-O terms, binary search connects to sorting and searching, backtracking builds on recursion, and many graph and tree problems reuse these patterns, see trees and graphs.
What you will learn
- βRecognise which of seven core patterns a problem is hinting at
- βUse two pointers on sorted data and on strings
- βWrite fixed-size and variable-size sliding windows
- βUse dictionaries and
Counterfor lookups, counting and prefix sums - βSolve matching and 'next greater' problems with a stack
- βApply binary search to a monotonic yes/no question instead of a list
- βWrite backtracking with choose, explore and undo
- βUse
heapqfor top-k and merging, and state the complexity of each pattern
Why programmers should learn this
- β Technical interviews for developer roles commonly include algorithm questions, and pattern recognition is the fastest way to make progress without memorising hundreds of problems.
- β Each pattern turns a slow brute-force approach (often O(n squared) or exponential) into something near-linear, which is the same skill you use when a real report or script is too slow.
- β Patterns give you a shared vocabulary for discussing solutions with other engineers: 'use a hash map for the complement' is a complete design idea in one sentence.
- β
Python's standard library already supplies the building blocks (
dict,Counter,deque,heapq,bisect), so learning the patterns also teaches you which tool to reach for. - β Practising with printed intermediate state teaches you to debug your own reasoning, a habit that carries over to every other kind of programming.
Two pointers: shrink from both ends or chase
The two-pointer pattern keeps two indexes into the same sequence and moves them according to a rule, so that a nested loop (O(n squared)) becomes a single pass (O(n)). It comes in two shapes. In the opposite ends shape one pointer starts at the left and one at the right, and they move toward each other. In the fast and slow shape both start on the left and the fast one scans ahead while the slow one marks where the next kept element goes.
Signals that point to it: the input is sorted (or you are allowed to sort it, which costs O(n log n) as discussed in sorting and searching); you are asked for a pair or triple with some property; you are asked to compare a string with its reverse; or you must modify an array in place without extra memory. The reason it works with sorted data is that each comparison tells you which pointer to move: if the sum is too small, only moving the left pointer up can make it larger, so everything you skip is provably useless.
The first example finds two numbers that add to a target in a sorted list, printing each decision. The second removes duplicates in place from a sorted list, using the slow and fast shape. Both use O(1) extra space, which is the reason interviewers like this pattern.
def pair_sum_sorted(nums, target):
left, right = 0, len(nums) - 1
while left < right:
s = nums[left] + nums[right]
print(f" left={left} right={right} sum={s}")
if s == target:
return nums[left], nums[right]
if s < target:
left += 1
else:
right -= 1
return None
data = [1, 3, 4, 6, 8, 11, 15]
print(pair_sum_sorted(data, 14))
print(pair_sum_sorted(data, 100))left=0 right=6 sum=16 left=0 right=5 sum=12 left=1 right=5 sum=14 (3, 11) left=0 right=6 sum=16 left=1 right=6 sum=18 left=2 right=6 sum=19 left=3 right=6 sum=21 left=4 right=6 sum=23 left=5 right=6 sum=26 None
Line by line
- 1-2Start with one pointer on each end of the sorted list.
- 3-5While the pointers have not met, compute the sum and print it so we can follow the search.
- 6-7Found the pair: return the two values.
- 8-11Sum too small: move the left pointer to a bigger number. Sum too big: move the right pointer to a smaller one.
- 12The pointers met without a match.
- 14-16Run on a sorted list with a target that exists (3 + 11) and one that does not.
def dedupe_sorted(nums):
if not nums:
return 0
slow = 0 # last position of the unique prefix
for fast in range(1, len(nums)):
if nums[fast] != nums[slow]:
slow += 1
nums[slow] = nums[fast]
return slow + 1
values = [1, 1, 2, 2, 2, 3, 5, 5]
k = dedupe_sorted(values)
print("unique count:", k)
print("prefix:", values[:k])
print("whole list after:", values)
def is_palindrome(text):
chars = [c.lower() for c in text if c.isalnum()]
i, j = 0, len(chars) - 1
while i < j:
if chars[i] != chars[j]:
return False
i += 1
j -= 1
return True
print(is_palindrome("A man, a plan, a canal: Panama"), is_palindrome("python"))unique count: 4 prefix: [1, 2, 3, 5] whole list after: [1, 2, 3, 5, 2, 3, 5, 5] True False
Line by line
- 1-3Empty input has zero unique values.
- 4
slowmarks the end of the unique prefix;fastscans every other position. - 5-8When
fastsees a new value, advanceslowand copy the value there. - 9The number of unique values is
slow + 1. - 11-15Dedupe a sorted list and show that only the prefix is meaningful; leftover values after it are ignored.
- 17-25Opposite ends again: clean the string, then compare characters from both ends moving inward.
- 27One palindrome, one not.
Complexity for both shapes is O(n) time and O(1) extra space once the data is sorted.
If the data is not sorted and you need the original indexes, two pointers on a sorted copy loses them. In that case a hash map (section 3) is the better tool.
Sliding window: contiguous ranges that grow and shrink
A sliding window is a range [left, right] that moves along an array or string. Instead of recomputing the answer for every range from scratch, you update it incrementally: add the element that enters on the right, remove the one that leaves on the left. That turns O(n x k) into O(n). Look for words like 'contiguous', 'substring', 'subarray', 'at most k' and 'longest or shortest range that satisfies a condition'.
There are two forms. In a fixed-size window the length k is given, so the window slides one step at a time and you keep a running total. In a variable-size window you expand right every step and shrink left while the window breaks a rule (for example it contains a repeated character). Each element enters the window once and leaves at most once, so even though there is a loop inside a loop, the total work is O(n).
The variable window is where people slip, so I print the window at every step. The key habit is to write the invariant, a sentence that is true after every iteration, for example 'the window s[left:right+1] has no repeated characters'. Whatever you do inside the shrinking loop must restore that sentence.
def best_window_sum(nums, k):
window = sum(nums[:k])
best, best_start = window, 0
for right in range(k, len(nums)):
window += nums[right] - nums[right - k] # add new, drop old
if window > best:
best, best_start = window, right - k + 1
return best, nums[best_start:best_start + k]
print(best_window_sum([2, 1, 5, 1, 3, 2, 9, 1], 3))(14, [3, 2, 9])
Line by line
- 2-3Sum the first window of size k and remember it as the best so far.
- 4-5Slide right one step: add the entering element and subtract the one that left. No inner loop needed.
- 6-7Track the best sum and where its window starts.
- 8Return the sum and the window itself.
- 10The best window of three is
[3, 2, 9]with sum 14.
def longest_unique(s):
last_seen = {} # character -> most recent index
left = 0
best = (0, "")
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1 # jump past the earlier copy
last_seen[ch] = right
window = s[left:right + 1]
print(f" right={right} ch={ch!r} window={window!r}")
if len(window) > best[0]:
best = (len(window), window)
return best
print(longest_unique("abcabcbb"))
print(longest_unique("pwwkew"))right=0 ch='a' window='a' right=1 ch='b' window='ab' right=2 ch='c' window='abc' right=3 ch='a' window='bca' right=4 ch='b' window='cab' right=5 ch='c' window='abc' right=6 ch='b' window='cb' right=7 ch='b' window='b' (3, 'abc') right=0 ch='p' window='p' right=1 ch='w' window='pw' right=2 ch='w' window='w' right=3 ch='k' window='wk' right=4 ch='e' window='wke' right=5 ch='w' window='kew' (3, 'wke')
Line by line
- 2Remember the last index of each character, so the left edge can jump instead of creeping.
- 5Expand the window by one character on the right each iteration.
- 6-7If this character already sits inside the window, move
leftjust past its previous position. This restores the 'no repeats' invariant. - 8-10Record the position and print the current window so you can watch it grow and jump.
- 11-12Keep the longest window seen.
- 16-17Two classic inputs; the answers have length 3 (
abc) and 3 (wke).
Both forms are O(n) time. Space is O(1) for the fixed window and O(alphabet size) for the character map.
For 'shortest subarray with sum at least target' the pattern is the same but the shrink loop runs while the window is *valid*, recording the length each time before shrinking. The condition flips; the structure does not.
Hash maps: trade memory for time
A dictionary gives average O(1) lookup, insertion and deletion, which makes it the most valuable tool in this lesson. The pattern: whenever you find yourself scanning the list again and again to ask 'have I seen X?' or 'how many of X are there?', store that information in a dictionary or set as you go. Brute-force O(n squared) pair searches become O(n) because the inner scan is replaced by one lookup. The cost is O(n) extra memory.
Three forms appear again and again. Complement lookup: for each number, check whether target - number was already seen (two-sum). Counting and grouping: use Counter or defaultdict(list) with a key that captures what makes items equivalent, such as the sorted letters of a word for anagrams. Prefix sums: store how many times each running total has occurred, so that 'how many subarrays sum to k' becomes a lookup of running - k.
The prefix-sum idea deserves a second look because it feels like magic. If the running total up to index j is P[j] and the running total up to an earlier index i is P[i], then the sum of the subarray between them is P[j] - P[i]. We want that to equal k, so we need an earlier prefix equal to P[j] - k. Counting how often each prefix has appeared gives the number of valid subarrays ending at j. It works even with negative numbers, which a sliding window cannot handle.
from collections import defaultdict
def two_sum(nums, target):
seen = {} # value -> index
for i, n in enumerate(nums):
need = target - n
if need in seen:
return seen[need], i
seen[n] = i
return None
print(two_sum([2, 7, 11, 15], 9))
print(two_sum([3, 2, 4], 6))
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
return sorted(groups.values())
print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))(0, 1) (1, 2) [['bat'], ['eat', 'tea', 'ate'], ['tan', 'nat']]
Line by line
- 3-10For each number, ask whether its complement has appeared. If yes, return both indexes; if not, remember this number's index.
- 12-13Indexes
(0, 1)for the first call and(1, 2)for the second; the second shows that a number is not paired with itself. - 15-19Words that are anagrams share the same sorted letters, so that string is the grouping key.
- 21Group six words into three anagram families (sorted for a stable print).
from collections import Counter
def count_subarrays(nums, k):
seen = Counter({0: 1}) # the empty prefix has sum 0
running = 0
total = 0
for n in nums:
running += n
hits = seen[running - k]
total += hits
seen[running] += 1
print(f" n={n:>2} running={running:>2} matches={hits}")
return total
print(count_subarrays([1, 2, 3, -2, 2], 3))
print(count_subarrays([1, 1, 1], 2))n= 1 running= 1 matches=0 n= 2 running= 3 matches=1 n= 3 running= 6 matches=1 n=-2 running= 4 matches=1 n= 2 running= 6 matches=1 4 n= 1 running= 1 matches=0 n= 1 running= 2 matches=1 n= 1 running= 3 matches=1 2
Line by line
- 4Before reading anything, one prefix (the empty one) has sum 0. Without this line, subarrays that start at index 0 would be missed.
- 5-6
runningis the sum of everything read so far;totalcounts matches. - 7-12For each number update the running sum, then add the number of earlier prefixes equal to
running - k, and record the current prefix. - 16-17The first list has four subarrays that sum to 3:
[1, 2],[3],[1, 2, 3, -2, 2 ...let the printed matches show which positions fire.
Time is O(n) and space O(n) for all three. Hash-map solutions assume good hashing; the worst case is O(n) per operation in theory but this almost never matters in practice.
Dictionary keys must be hashable. Use tuples, not lists, as keys, and remember that grouping by sorted(w) needs "".join(...) to become a string or tuple(...).
Stacks: matching, nesting and next greater element
A stack is last-in, first-out, and in Python a plain list with append and pop is the stack. Reach for it when the most recently seen thing is the next thing that must be resolved. The textbook cases are matching brackets, evaluating expressions, undoing operations and walking a nested structure without recursion. See stacks and queues for the data structure itself.
A more subtle use is the monotonic stack: a stack whose values are kept in sorted order by popping anything that violates the order before pushing. It answers questions like 'for each day, how many days until a warmer temperature?' or 'what is the next greater element?' in O(n). Each element is pushed once and popped once, so the total is linear even though a while loop sits inside the for.
The thinking is: the stack holds the indexes still waiting for an answer. When a new value arrives that is bigger than the value at the top, that waiting index has just found its answer, so pop it and record the distance. Keep popping while the condition holds, then push the new index. The first example validates brackets, the second computes the warmer-day waiting times.
def valid_brackets(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
for text in ["([]{})", "([)]", "((", "]"]:
print(f"{text!r:10} -> {valid_brackets(text)}")'([]{})' -> True
'([)]' -> False
'((' -> False
']' -> FalseLine by line
- 2Map each closing bracket to the opener it must match.
- 4-6Push every opening bracket.
- 7-9A closing bracket must match the most recent opener; if the stack is empty or the top differs, the string is invalid.
- 10At the end the stack must be empty, otherwise some opener was never closed.
- 12-13Four test strings, covering valid, wrongly nested, unclosed and starting with a closer.
def days_until_warmer(temps):
answer = [0] * len(temps)
waiting = [] # indexes whose answer is not known yet
for i, t in enumerate(temps):
while waiting and temps[waiting[-1]] < t:
j = waiting.pop()
answer[j] = i - j
print(f" day {i} ({t}) answers day {j} ({temps[j]}): wait {i - j}")
waiting.append(i)
return answer
print(days_until_warmer([73, 74, 75, 71, 69, 72, 76, 73]))day 1 (74) answers day 0 (73): wait 1 day 2 (75) answers day 1 (74): wait 1 day 5 (72) answers day 4 (69): wait 1 day 5 (72) answers day 3 (71): wait 2 day 6 (76) answers day 5 (72): wait 1 day 6 (76) answers day 2 (75): wait 4 [1, 1, 4, 2, 1, 1, 0, 0]
Line by line
- 2Default answer 0 means 'no warmer day ever comes'.
- 3The stack stores indexes of days still waiting; their temperatures are non-increasing from bottom to top.
- 4-7For each new day, while it is warmer than the day on top, pop that day and record how long it waited.
- 8Push today; it now waits for something warmer.
- 12Prints the wait for each day; the printed trace explains every pop.
Both run in O(n) time with O(n) space in the worst case.
Store indexes rather than values in a monotonic stack. You can always look up the value from the index, but you cannot recover the index from the value, and distances need indexes.
Binary search on the answer
You already know binary search for finding a value in a sorted list (see sorting and searching). The more powerful version searches over possible answers rather than over array positions. The signal is a question like 'what is the smallest speed, capacity or size for which this is possible?' where you can write a function feasible(x) that checks a candidate in O(n), and where feasibility is monotonic: once it becomes true for some x, it stays true for every larger x (or the reverse).
When the answer space looks like False False False True True True, you can binary search for the boundary. Pick the middle candidate; if it is feasible, the answer is that or something smaller, so keep the left half including mid; if it is not, discard it and everything below. The loop while lo < hi with hi = mid on success and lo = mid + 1 on failure converges on the first feasible value without off-by-one trouble.
The total cost is O(n log R), where R is the size of the range of candidate answers. The classic examples are the smallest eating speed that finishes all piles within H hours, the smallest ship capacity to deliver packages within D days and the integer square root. The hard part is never the search; it is defining the feasibility check and picking the correct bounds: lo is the smallest conceivable answer, hi is a value that is definitely enough.
def hours_needed(piles, speed):
return sum(-(-p // speed) for p in piles) # ceiling division
def min_speed(piles, hours):
lo, hi = 1, max(piles) # speed max(piles) always works if hours >= len(piles)
while lo < hi:
mid = (lo + hi) // 2
need = hours_needed(piles, mid)
print(f" try speed {mid:>2}: needs {need} hours")
if need <= hours:
hi = mid # feasible: try slower
else:
lo = mid + 1 # too slow: need faster
return lo
piles = [3, 6, 7, 11]
print("answer:", min_speed(piles, 8))
print("answer:", min_speed([30, 11, 23, 4, 20], 6))
# integer square root: the same idea over numbers
def isqrt(n):
lo, hi = 0, n
while lo < hi:
mid = (lo + hi + 1) // 2
if mid * mid <= n:
lo = mid
else:
hi = mid - 1
return lo
print([isqrt(n) for n in (0, 1, 15, 16, 99, 100)])try speed 6: needs 6 hours try speed 3: needs 10 hours try speed 5: needs 8 hours try speed 4: needs 8 hours answer: 4 try speed 15: needs 8 hours try speed 23: needs 6 hours try speed 19: needs 8 hours try speed 21: needs 7 hours try speed 22: needs 7 hours answer: 23 [0, 1, 3, 4, 9, 10]
Line by line
- 1-2The feasibility check: at a given speed each pile takes
ceil(p / speed)hours.-(-p // speed)is a trick for ceiling division with integers. - 4-5Candidate speeds range from 1 to the largest pile (eating faster than the biggest pile cannot help).
- 6-8Look at the middle speed and compute its total hours; print it to watch the range shrink.
- 9-12Feasible: the answer is
midor lower, so sethi = mid. Not feasible: it must be abovemid. - 13When
lomeetshiwe have the smallest feasible speed. - 15-17The first call returns 4; the second returns 23, with trace lines showing every probe.
- 20-28The same template finding the largest
xwithx * x <= n. Because we keeploon success, the middle is rounded up to avoid an infinite loop.
Interviewers often hide this pattern. If the brute-force solution is 'try every possible answer from 1 upward and check', and checking is monotonic, you have found it.
When the success branch keeps mid in the range (lo = mid), round the middle up with (lo + hi + 1) // 2. Otherwise lo can stay stuck and the loop never ends.
Backtracking: choose, explore, undo
Backtracking builds candidates one decision at a time and abandons a path as soon as it cannot lead to a valid answer. It is the right tool for 'generate all subsets, permutations, combinations or placements that satisfy some constraint'. It is recursion with a very specific shape: choose an option, explore recursively with that option included, then undo the choice so the next option starts from a clean state. See recursion if that rhythm feels unfamiliar.
The cost is usually exponential (2 to the n for subsets, n factorial for permutations), so the skill is pruning: stop early when the partial path already breaks a rule. Sorting the input first helps prune and also makes it easy to skip duplicates. The size of the output is the lower bound on the work, so when a problem asks for all answers you cannot beat exponential time; when it asks only for the number of answers, consider dynamic programming instead (see dynamic programming).
Two details cause most bugs. First, when you add a finished path to the results you must add a copy (path[:] or list(path)), because the same list keeps changing afterwards. Second, the undo step must exactly reverse the choice. The examples below generate subsets that add up to a target (with pruning) and then permutations, and I print the choices as they happen in the first one so you can see the undo.
def combos(candidates, target):
candidates = sorted(candidates)
results = []
def go(start, path, remaining):
if remaining == 0:
results.append(path[:]) # copy!
return
for i in range(start, len(candidates)):
c = candidates[i]
if c > remaining:
break # prune: sorted, so the rest are too big
path.append(c) # choose
go(i, path, remaining - c) # explore (same i: reuse allowed)
path.pop() # undo
go(0, [], target)
return results
print(combos([2, 3, 6, 7], 7))
print(combos([2, 3, 5], 8))[[2, 2, 3], [7]] [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
Line by line
- 1-3Sort so that we can stop scanning as soon as a candidate is too big.
- 5-8When nothing remains to add, we have a valid combination; store a copy of the current path.
- 9-12Try each candidate from
startonward. Passing the same index again lets a number be reused; starting atirather than 0 avoids counting the same combination in a different order. - 13-15Choose, recurse and undo.
pop()restores the path exactly as it was. - 17-18Start the search from an empty path.
- 20-21The first call finds
[2, 2, 3]and[7]; the second finds[2, 2, 2, 2],[2, 3, 3]and[3, 5].
def permutations(items):
results = []
used = [False] * len(items)
def go(path):
if len(path) == len(items):
results.append(tuple(path))
return
for i, x in enumerate(items):
if used[i]:
continue
used[i] = True
path.append(x)
go(path)
path.pop()
used[i] = False
go([])
return results
for p in permutations("abc"):
print("".join(p))
print(len(permutations(range(5))))abc acb bac bca cab cba 120
Line by line
- 2-3
used[i]records which items are already in the current path. - 5-8A path with every item is a complete permutation; store it as a tuple (an immutable copy).
- 9-16Try every unused item: mark it, add it, recurse, then remove it and unmark it, which is the undo step.
- 19-21Print the six permutations of
abcand count the 120 of five items, which is 5 factorial.
Subsets are O(2^n), permutations O(n x n!), and the stack depth is O(n).
Python's itertools has permutations, combinations and product for the plain cases. Write backtracking yourself when you need pruning or custom constraints, which is exactly what interviews test.
Heaps and top-k
A heap keeps the smallest item instantly available. Python's heapq module implements a min-heap on a plain list: heappush and heappop cost O(log n), and heap[0] peeks at the minimum in O(1). Use a heap whenever you repeatedly need 'the best remaining item': k largest elements, the kth smallest, merging k sorted lists, scheduling the earliest task or running Dijkstra's shortest path on a graph from trees and graphs.
The top-k trick is counter-intuitive: to keep the k largest items, you maintain a min-heap of size k. For each new value, push it; if the heap grows beyond k, pop the smallest. Whatever remains is the k largest, and the smallest of them sits at the top, which is exactly the kth largest. That costs O(n log k) time and O(k) memory, compared with O(n log n) for sorting everything. It also works on streams that are too big to hold in memory.
Because heapq only does min-heaps, store negated numbers (or tuples such as (-count, word)) for a max-heap. Tuples compare element by element, so ties are broken by the second element, which gives deterministic results. For simple cases, heapq.nlargest(k, data, key=...) is a clean one-liner; write the loop by hand when the interviewer wants to see the idea. heapq.merge does a lazy merge of already sorted iterables.
import heapq
from collections import Counter
def kth_largest(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest of the k+1
print(f" after {x:>2}: heap holds {sorted(heap)}")
return heap[0]
print("3rd largest:", kth_largest([3, 2, 1, 5, 6, 4, 9], 3))
# top-k frequent words, ties broken alphabetically
words = "the cat and the dog and the bird saw the cat".split()
counts = Counter(words)
top = heapq.nsmallest(3, counts.items(), key=lambda kv: (-kv[1], kv[0]))
print(top)
# merge several sorted lists lazily
print(list(heapq.merge([1, 4, 9], [2, 3, 10], [0, 5])))
# max-heap by negating
h = []
for x in (4, 1, 7, 3):
heapq.heappush(h, -x)
print("largest:", -heapq.heappop(h), "then", -heapq.heappop(h)) after 3: heap holds [3]
after 2: heap holds [2, 3]
after 1: heap holds [1, 2, 3]
after 5: heap holds [2, 3, 5]
after 6: heap holds [3, 5, 6]
after 4: heap holds [4, 5, 6]
after 9: heap holds [5, 6, 9]
3rd largest: 5
[('the', 4), ('and', 2), ('cat', 2)]
[0, 1, 2, 3, 4, 5, 9, 10]
largest: 7 then 4Line by line
- 1-2Import the heap functions and
Counter. - 4-11Keep a heap of at most k values. Each push may make it k+1 long; popping then removes the smallest so only the k largest remain.
- 12After the loop the top of the heap is the kth largest value: 5 for k = 3 in this list.
- 14-18Count words, then ask for the three most frequent. The key
(-count, word)sorts higher counts first and breaks ties alphabetically. - 20-21
heapq.mergecombines sorted inputs into one sorted stream without building all of it at once. - 23-27A max-heap by pushing negative numbers and negating again when popping.
Building a heap from a list with heapify is O(n); each push or pop is O(log n); top-k with a size-k heap is O(n log k).
Heap order is not sorted order. Printing the raw heap list shows a partly ordered array, not a sorted one. That is why the trace above prints sorted(heap).
Recognising patterns, complexity, and a practice habit
Here is the recognition table I use. Sorted input and pairs point to two pointers. A contiguous range with a condition points to a sliding window. 'Have I seen this' or 'count by key' points to a hash map. Nested or matching structure, or 'next greater', points to a stack. 'Smallest value that works' with a yes/no check points to binary search on the answer. 'Generate all' points to backtracking, and 'k best' or 'repeatedly the smallest' points to a heap. If the question asks for a count or optimum over choices with overlapping states, consider dynamic programming.
When you are stuck, do not stare at the problem. Write the brute force, say its complexity aloud, and ask which repeated work you could avoid. That is how every pattern in this page was discovered. State the time and space complexity of your final answer with reference to input size, as explained in Big-O, and name the trade-off you made, for example extra memory for speed.
My strongest practice habit is to check a clever solution against a brute-force one on many small random inputs. Interview-style bugs hide in edge cases: empty input, one element, duplicates, negative numbers, everything equal. A short test harness catches these in seconds. The block below does exactly that for the sliding-window maximum-sum idea, using a seeded random generator so the output is repeatable, and then prints the recognition table.
import random
def best_sum_fast(nums, k):
window = sum(nums[:k])
best = window
for r in range(k, len(nums)):
window += nums[r] - nums[r - k]
best = max(best, window)
return best
def best_sum_brute(nums, k):
return max(sum(nums[i:i + k]) for i in range(len(nums) - k + 1))
random.seed(7)
for trial in range(1000):
n = random.randint(1, 8)
nums = [random.randint(-5, 9) for _ in range(n)]
k = random.randint(1, n)
assert best_sum_fast(nums, k) == best_sum_brute(nums, k), (nums, k)
print("1000 random cases agree")
table = [
("sorted input, pair/triple", "two pointers", "O(n)", "O(1)"),
("contiguous range with a rule", "sliding window", "O(n)", "O(1) to O(k)"),
("seen before? count by key?", "hash map / set", "O(n)", "O(n)"),
("matching, next greater element", "stack", "O(n)", "O(n)"),
("smallest x that works (monotonic)", "binary search answer","O(n log R)", "O(1)"),
("generate all valid arrangements", "backtracking", "O(2^n)/O(n!)","O(n)"),
("k best, repeated minimum, merge", "heap", "O(n log k)", "O(k)"),
]
print()
for signal, pattern, time, space in table:
print(f"{signal:<36} {pattern:<21} {time:<13} {space}")1000 random cases agree sorted input, pair/triple two pointers O(n) O(1) contiguous range with a rule sliding window O(n) O(1) to O(k) seen before? count by key? hash map / set O(n) O(n) matching, next greater element stack O(n) O(n) smallest x that works (monotonic) binary search answer O(n log R) O(1) generate all valid arrangements backtracking O(2^n)/O(n!) O(n) k best, repeated minimum, merge heap O(n log k) O(k)
Line by line
- 3-9The fast sliding-window solution from earlier.
- 11-12A slow but obviously correct solution: sum every window of size k.
- 14Seed the random generator so every run produces the same cases.
- 15-20Generate 1000 tiny random inputs, including negatives, and assert that the two functions agree. An
AssertionErrorwould print the failing case. - 21If we get here, no counterexample was found.
- 23-31A list of tuples summarising the signals, patterns and their complexity.
- 32-34Print them as aligned columns using format widths.
After solving a problem, ask what would change if the input were sorted, streamed, enormous or full of duplicates. Those variations are the usual follow-up questions.
Common mistakes
β Using two pointers on unsorted data
The 'move the pointer that fixes the sum' logic only works because sorting guarantees what each move does. On unsorted data use a hash map or sort first.
β Not restoring the window invariant
In a variable sliding window, the shrinking loop must run until the rule holds again. Forgetting to remove the outgoing element from your counters makes answers wrong in subtle ways.
β Forgetting the empty prefix in prefix sums
Initialising the counter with {0: 1} is what counts subarrays that begin at index 0. Leave it out and those answers disappear.
β Appending the live list in backtracking
results.append(path) stores a reference to a list that keeps changing. Append path[:] or a tuple, and make sure the undo step exactly reverses the choice.
β Binary search that never ends
If the success branch sets lo = mid, compute mid rounding up. Also check that your feasibility function really is monotonic before searching on it.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. Which signal most strongly suggests a sliding window?
Q2. Why does the two-pointer pair-sum technique need sorted input?
Q3. What is the time complexity of the monotonic stack solution for 'next warmer day'?
Q4. To keep the k largest numbers from a stream with heapq, which structure do you maintain?
Q5. What must be true to binary search on the answer?
Q6. Why do we append path[:] rather than path to the results in backtracking?
Frequently asked questions
How many problems do I need to practise?
+There is no magic number. Quality matters more than quantity: after each problem, name the pattern, write its complexity and redo it a few days later without looking. Ten problems per pattern with review beats a hundred problems skimmed.
Which Python tools should I know for interviews?
+dict, set, Counter, defaultdict, deque, heapq, bisect, sorted with a key, slicing and enumerate. The standard library already covers most data structures you will be asked to use.
Should I explain my solution before coding?
+Yes. State the brute force, its complexity, the pattern that improves it and the final complexity, then code. Interviewers are usually evaluating your reasoning as much as the code.
What if I do not recognise the pattern?
+Start with the brute force, test it on a tiny example by hand, and look for repeated work or for a property such as sortedness or monotonicity. Often the pattern appears once you write down what is being recomputed.
Do these patterns matter outside interviews?
+They do. Windows over logs, hash lookups to join records, heaps for scheduling and binary search for tuning a limit are all everyday engineering problems; interviews simply compress them into small puzzles.
Key takeaways
- βMost interview problems are variations of a handful of patterns; learn to recognise the signals first and the code second.
- βTwo pointers and sliding windows turn nested loops into a single O(n) pass for sorted data and contiguous ranges.
- βHash maps trade O(n) memory for O(1) lookups, and prefix sums extend the idea to subarray questions.
- βStacks resolve the most recent unresolved item, and a monotonic stack answers next-greater questions in linear time.
- βBinary search works on any monotonic yes/no question, and backtracking with pruning generates valid arrangements using choose, explore and undo.
- βHeaps give top-k in O(n log k); always state your complexity and test against a brute force on small random inputs.