Algorithms and data structures
Big O tells you how the work grows when the data grows. Pick the right data structure (a list, a hash set, a sorted list, a heap) and most slow code becomes fast. In an interview, start simple, find the cost, then improve it.
Author: bezzad
Contents
The problem: fast in tests, slow in production
Our online shop has a “Sale” badge. Every night a job marks the products that are on sale. The code is:
def mark_sale_products(products: list[dict], sale_ids: list[int]) -> None:
for product in products:
product["on_sale"] = product["id"] in sale_ids
- In tests we have 20 products and 5 sale ids. The job takes one millisecond.
- In production we have 200,000 products and 50,000 sale ids. The job takes many minutes, and the CPU is at 100%.
- The data grew about 10,000 times. But the time grew much more than that.
The code is correct. The problem is the algorithm. The in operator on a list is a hidden loop. It checks the items one by one. So we have a loop inside a loop.
The fix is one line:
def mark_sale_products(products: list[dict], sale_ids: list[int]) -> None:
sale = set(sale_ids) # build once
for product in products:
product["on_sale"] = product["id"] in sale
To see why this one line helps, we need two ideas: Big O, and data structures.
Big O in simple words
Big O does not give the exact time. It tells you how the amount of work grows when the input grows.
- We count steps, not seconds. A step is one simple action, like comparing two numbers.
- We look at big inputs. Small inputs are fast with any algorithm.
- We drop constants. Two loops one after the other are 2n steps. We still write O(n), because both grow in the same way.
- We usually think about the worst case. For example, the item we search for is not in the list at all.
| Big O | Name | Example | Steps for 1 million items |
|---|---|---|---|
| O(1) | Constant | Read an item by index. Look up a key in a hash set. | 1 |
| O(log n) | Logarithmic | Binary search in a sorted list. | about 20 |
| O(n) | Linear | One loop over all items. | 1 million |
| O(n log n) | “n log n” | A good sort. | about 20 million |
| O(n²) | Quadratic | A loop inside a loop. | 1,000 billion |
Back to our job. The outer loop runs n times. The hidden loop inside runs m times. So the first version is O(n·m). That is 200,000 × 50,000 = 10 billion steps in the worst case. The second version builds the set once (m steps) and then does one fast lookup for each product (n steps). That is O(n + m): about 250,000 steps.
Choose the number of items. We count the steps, and we pretend that one step takes one microsecond. The bars use a log scale, so a bar twice as long means much more than twice the work.
The data structures you really need
A data structure is a way to keep data in memory. Each one is fast at some things and slow at others. Choosing the right one is most of the work.
A list (an array)
The items sit next to each other in memory, in order.
- Fast: read or change an item by its index. Add an item at the end.
- Slow: search for a value (O(n)). Add or remove an item at the start or in the middle (O(n)), because all the next items must move.
A hash set and a hash map (a dict)
A set keeps unique values. A dict keeps key and value pairs. Both use a hash.
- A hash function turns the key into a number.
- That number points to a “bucket”, a place in memory.
- To find a key, we compute its hash and go straight to its bucket. We do not check the other items.
- So lookup, add and remove are O(1) on average.
- The catch: two different keys can land in the same bucket (a collision). With a bad hash function, many keys land in one bucket, and the lookup becomes slow. With normal keys like numbers and strings, this is rare.
- Keys must be hashable. In Python, a list cannot be a key, but a tuple can.
A sorted structure (a tree)
Sometimes we need order: “products between 10 and 20 dollars” or “the next appointment after now”. A hash set cannot answer these questions fast.
- A sorted list with binary search finds an item in O(log n). But adding an item in the middle is O(n).
- A balanced tree keeps the data sorted, and finds, adds and removes in O(log n).
- Databases use a similar tree (a B-tree) for indexes. This is why an index makes a query fast.
A queue, a stack and a heap
- A queue: first in, first out. Orders wait for processing in the order they came. In Python, use collections.deque. Removing the first item of a normal list is O(n), but on a deque it is O(1).
- A stack: last in, first out. The “undo” button works like this. A normal list is fine for a stack: add and remove at the end.
- A heap: gives you the smallest item fast. Adding and removing is O(log n). It is good for “the 10 best-selling products out of a million” (top-k). In Python, use the heapq module.
Search: linear and binary
Linear search checks the items one by one. It works on any list. It is O(n).
Binary search works only on a sorted list. It is like finding a word in a paper dictionary:
- Look at the middle item.
- If it is the target, you are done.
- If the target is bigger, throw away the left half. If it is smaller, throw away the right half.
- Repeat on the half that is left.
Binary search is easy to explain and easy to get wrong. Most bugs are “off by one”: the loop stops one step too early, or never stops. Use the standard library when you can:
from bisect import bisect_left
def contains(sorted_ids: list[int], target: int) -> bool:
i = bisect_left(sorted_ids, target) # first position where target could go
return i < len(sorted_ids) and sorted_ids[i] == target
If you must write it yourself in an interview, say the rule of the loop out loud: “if the target exists, it is always between low and high, both included.” Then test it on an empty list, a list with one item, and a target at the first and the last position.
Sorting
- Use the built-in sort. In Python, that is the sorted function or the sort method. It is O(n log n) and it is well tested.
- It is stable. Items with equal keys keep their old order. So you can sort by name first, and then by price, and products with the same price stay sorted by name.
- Sorting often makes the next step easy. After sorting, equal items sit next to each other. So finding duplicates becomes one simple loop.
- Writing your own sort is only for an interview question or a very special case.
# Cheapest first; for the same price, newest first
products.sort(key=lambda p: (p["price"], -p["created_at"]))
How to solve an algorithm question in an interview
The interviewer wants to see how you think, not only the final code.
- Ask questions first. How big is the input? Can it be empty? Are there duplicates? Is it sorted? Is memory limited?
- Say the simple solution. Even if it is slow. “A loop inside a loop works. It is O(n²).”
- Find what is slow. Usually it is a repeated search. Ask: “Can a set, a dict, sorting or a heap remove this repeated work?”
- Write the better solution. Use clear names. Keep it small.
- Test it by hand. Walk through a small example. Then edge cases: empty input, one item, all items the same.
- Say the cost. Time and memory. And say what you would choose in a real project, and why.
Common mistakes
| Mistake | Result | The right way |
|---|---|---|
| Using in on a list inside a loop | O(n²) work, the job gets slow when the data grows. | Build a set or a dict once, before the loop. |
| Testing only with tiny data | The slow part is found in production. | Test with realistic sizes, or think about Big O in review. |
| Removing the first item of a list again and again | Every removal moves all the other items. | Use a deque for a queue. |
| Sorting the whole list to get the top 10 | O(n log n) work, when much less is enough. | Use a heap (heapq.nlargest) for the top k items. |
| Writing your own binary search or sort | Off-by-one bugs. | Use bisect and the built-in sort. |
| Making code clever before it is needed | The code is hard to read, and the gain is tiny. | For small data, simple code wins. Measure first. |
| Loading all rows from the database to filter them in code | Memory, time and network grow with the table. | Filter, sort and join in the database, with an index. |
Summary in six lines
- Big O tells you how the work grows when the data grows, not the exact time.
- A loop inside a loop is O(n²). Look for hidden loops, like the in operator on a list.
- A hash set or a dict finds a key in O(1) on average. Build it once, then look up many times.
- For order and ranges, use a sorted structure. Binary search is O(log n), but only on sorted data.
- Use the built-in sort, bisect, deque and heapq. They are fast and well tested.
- In an interview: ask, start simple, find the slow part, improve, test edge cases, and say the cost.