Lesson 40 of 40Strings, math and design
Wrap-Up: Algorithms & Patterns
Tie the whole Algorithms track together: one real search feature built from sizing to tests with the patterns you learned, a mixed review, and where to go next.
You started this track with Big-O and a question about why one solution finishes in a blink while another runs until lunch. Since then you have learned the core data structures, the array patterns, trees and graphs, dynamic programming in its main shapes, and finally strings, math, range queries and design problems. On the job these never arrive one per ticket. This lesson lines them up once more and then uses them together on one piece of work.
The path you took
Unit 1
Foundations
Big-O, a cost table for every core structure and a method for any problem. That gave you a way to judge every pattern that followed.
Unit 2
Core patterns
Hashing, two pointers, sliding windows, stacks, binary search and linked lists turned many O(n²) loops into one pass.
Unit 3
More array patterns
Prefix sums, monotonic stacks and matrix tricks extended those passes to ranges, next-greater questions and grids, which are graphs in disguise.
Unit 4
Trees and graphs
Trees, tries, heaps, BFS, DFS and backtracking taught you to walk structures with branches, the base for every harder graph problem.
Unit 5
Graphs in depth
Union-find, shortest paths, cycle detection and spanning trees let you pick the right graph algorithm from the edge weights and the question.
Unit 6
Advanced patterns
Dynamic programming, greedy, intervals, bits and sorting showed you when to cache subproblems and when one safe choice is enough.
Unit 7
DP families
Knapsack, sequence, interval, bitmask and tree DP gave you a shelf of state shapes to try, so a new DP problem starts from a template.
Unit 8
Strings, math and design
String algorithms, modular maths, range queries and class design closed the gaps and showed several structures working inside one class.
How it fits together
The ticket: "Build the suggestions service for the shop's search box. As the user types, show up to five matching products, a 'trending in the last hour' list, a 'did you mean' fix for typos and a few related searches. There are about 2 million product names and 5,000 requests a second at peak. Each request has a 20 ms budget." Here is how the track shows up, in the order you would really work.
Sizing it first. Before any code you do the arithmetic from Big-O Notation. Scanning 2 million names on every keystroke is 2 million comparisons times 5,000 requests a second, which is far past any budget. So each request must cost about the length of the prefix, or log n, not n. How to Solve Problems tells you to state the brute force anyway, with its cost, because you will use it later to test the fast version.
Cleaning the input. Users type "Café", "cafe" and "CAFÉ". String Algorithms reminded you that length and equality depend on the Unicode form, so you normalise and lowercase once, at the edge, before anything is stored or looked up.
Autocomplete. "Does anything start with this?" is the question Tries answers in time set by the prefix length. Each node also keeps its top five products by popularity, so a lookup never has to walk the subtree. You weigh the simpler option too: sort the names once (Sorting) and use the boundary search from Binary Search to find the first and last name with that prefix. That needs far less memory. The trie wins only if you need those per-node top five lists, and the cost table from Data Structures Overview makes that trade explicit.
Trending in the last hour. Each search bumps a counter in a hash map, the core move from Arrays and Hashing. "The last hour" is a window that slides, so you keep one bucket of counts per minute in a deque. A new minute is added and the expired one is subtracted, as in Sliding Window. Picking the top 10 from thousands of queries is the top k pattern from Heaps: a min-heap of size 10, so the cost is n log 10, not a full sort. If product later asks for counts over any time range in the last day, per-minute totals with prefix sums from Prefix Sums and Difference Arrays answer it in O(1). Only if updates and range queries interleave heavily do you need a Fenwick tree from Fenwick Trees, Segment Trees and Sorted Containers, and that lesson's honest advice applies: most services never do.
Did you mean. A typo fix is edit distance from 2D Dynamic Programming, kept to two rows of memory. Running it against 2 million names is too slow, so you prune: walk the trie and stop any branch whose best possible distance is already above 2. That is the pruning idea from Backtracking, applied to a DP table one row per trie level.
Related searches. Queries that appear in the same session become edges in a graph (Graphs), weighted by how often they co-occur. Related searches are the nearest neighbours within two hops, found with a BFS that marks nodes when it pushes them. Spelling variants that should count as one query, like "tshirt" and "t-shirt", are merged with Union-Find in Depth, so every counter and edge uses the group's root.
Caching hot prefixes. A few prefixes like "i" and "ip" get most of the traffic. An LRU cache in front of the trie, built exactly as in Design Problems: LRU Cache, Iterators and Friends, serves them in O(1). The senior follow-up from that lesson applies: many threads share it, so you shard it by key with a lock per shard.
Proving it works. You keep the brute force from day one. A stress test generates random names and prefixes, compares the trie's answers with a plain scan, and shrinks any failure to the smallest input. Then you write down the complexity of each endpoint the way Analyzing Code taught: what it costs per request, what it costs in memory, and where the hidden costs are, such as string slicing inside a loop.
No pattern was used alone. The hash map fed the heap, the trie carried the DP, the graph depended on union-find to agree on names, and Big-O decided every choice before a line was written.
Check yourself
for i in range(n): j = n; while j > 1: j //= 2What does this print?
nums = [1, 1, 1]
k = 2
seen = {0: 1}
total = count = 0
for x in nums:
total += x
count += seen.get(total - k, 0)
seen[total] = seen.get(total, 0) + 1
print(count, seen)Match each problem to the pattern you would try first.
What does this print?
import heapq h = [] for x in [5, 1, 4, 2]: heapq.heappush(h, x) print(heapq.heappop(h), h[0])
Put the steps of solving a new problem in a sensible order.
- Tap the steps below in the right order.
What you can do now
- Work out the time and space of most code you read, including recursion, amortized appends and hidden costs.
- Pick the right built-in structure in Python or TypeScript from the operations a task needs.
- Recognise and write the core patterns: hashing, two pointers, sliding window, stacks, binary search, prefix sums and linked-list pointer work.
- Walk trees and graphs with DFS and BFS, and choose between topological sort, union-find, Dijkstra and the other shortest-path algorithms.
- Define a DP state in words, fill a 1D or 2D table, and tell when greedy is safe instead.
- Design a class like an LRU cache with an exact cost per method.
That is a solid level for most coding interviews and for everyday performance work. What it is not yet is speed under a clock, or fluency on problems that hide their pattern. That comes from deliberate practice and from the next course.
Mistakes that still catch people
- Off-by-one boundaries. A loop that stops one short, or a prefix array without the leading zero. Revisit Binary Search and Prefix Sums and Difference Arrays.
- Trusting a greedy rule without a proof. It passes the examples and fails on a hidden test. Revisit Greedy Algorithms and Dynamic Programming.
- Marking visited at the wrong moment. Marking on pop instead of push, or using one visited set for a directed cycle check. Revisit Graphs and Cycles, Ordering and Bipartite Graphs.
- Hidden linear costs.
list.pop(0), string slicing orinon a list inside a loop. Revisit Analyzing Code and Data Structures Overview. - Recursion that is too deep. A path-shaped tree of 10^5 nodes blows Python's stack. Revisit Recursion to Iteration and Trees.
- Heap entries that compare the payload. A tie makes Python compare two objects and crash. Revisit Heaps.
Where to go next
The natural next course is Problem Solving. This track taught you the patterns. That one teaches the step before them: reading a new problem, using the constraints as hints, and talking through a solution under a clock. After it, System Design takes the suggestions service from this lesson and asks how to run it on many machines, and Interview Prep pulls everything into a plan for real rounds.
Real practice matters as much as the next course:
- Work through one curated problem list. Finish it in order, keep a log of what you got wrong, and redo those problems a week later.
- Build something that needs a structure. A small autocomplete, a route planner or a rate limiter, with a brute-force test beside it.
- Read the official docs for your toolkit. The Python pages for
collections,heapqandbisect, and MDN's pages onMap,SetandArray.prototype.sort, answer most "what does this cost" questions.
- time-space trade-off
- Spending extra memory, such as a hash map or a cache, to avoid repeated work and cut the running time.
- invariant
- A rule your loop or class keeps true at every step, like 'the window has no repeats'. Most bugs are a broken invariant.
- brute force
- The simplest correct solution, stated with its cost and kept as a reference to test faster versions against.
- amortized cost
- The average cost per operation over a long sequence, even if a few operations are slow, as with appending to a dynamic array.
- state
- In DP or search, the smallest set of facts that fully describes a subproblem, said in words before you write code.
- pruning
- Stopping a branch of a search as soon as it cannot lead to a valid or better answer.
- frontier
- The set of nodes waiting to be explored in BFS, DFS or Dijkstra, held in a queue, stack or heap.