My account

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.

Not reviewedWritten with AI helpReading time: 15 minOnline shop examplePython code

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
  1. In tests we have 20 products and 5 sale ids. The job takes one millisecond.
  2. In production we have 200,000 products and 50,000 sale ids. The job takes many minutes, and the CPU is at 100%.
  3. 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.

  1. We count steps, not seconds. A step is one simple action, like comparing two numbers.
  2. We look at big inputs. Small inputs are fast with any algorithm.
  3. We drop constants. Two loops one after the other are 2n steps. We still write O(n), because both grow in the same way.
  4. We usually think about the worst case. For example, the item we search for is not in the list at all.
WorkInput sizeO(n²)O(n log n)O(n)O(log n)O(1)
When the data grows, the gap between the curves becomes huge. The shape of the curve matters more than a fast computer.
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.

Live example: how the work grows

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.

Space also has a Big O. The set uses extra memory: O(m). Very often we trade memory for speed. In an interview, say both costs: “This is O(n) time and O(n) extra space.”

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.

  1. Fast: read or change an item by its index. Add an item at the end.
  2. 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.

  1. A hash function turns the key into a number.
  2. That number points to a “bucket”, a place in memory.
  3. To find a key, we compute its hash and go straight to its bucket. We do not check the other items.
List: check one by one4279315612877501234567Seven checks to find 77. With n items, up to n checks.Hash set: compute the place77hash(77) % 8 = 5012345674228777One step. The size of the set does not matter.
A list checks items one by one. A hash set computes where the key is and goes straight there.
  1. So lookup, add and remove are O(1) on average.
  2. 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.
  3. 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.

  1. A sorted list with binary search finds an item in O(log n). But adding an item in the middle is O(n).
  2. A balanced tree keeps the data sorted, and finds, adds and removes in O(log n).
  3. 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

  1. 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).
  2. 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.
  3. 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:

  1. Look at the middle item.
  2. If it is the target, you are done.
  3. If the target is bigger, throw away the left half. If it is smaller, throw away the right half.
  4. Repeat on the half that is left.
1381217212630343945515662707784Middle is 34. 34 < 62, so drop the left half.2381217212630343945515662707784Middle is 56. 56 < 62, so drop the left half.3381217212630343945515662707784Middle is 70. 70 > 62, so drop the right half.4381217212630343945515662707784Middle is 62. Found in 4 steps.
Each step throws away half of the list. Sixteen items need at most four or five steps. One million items need about 20.

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

  1. 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.
  2. 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.
  3. Sorting often makes the next step easy. After sorting, equal items sit next to each other. So finding duplicates becomes one simple loop.
  4. 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.

  1. Ask questions first. How big is the input? Can it be empty? Are there duplicates? Is it sorted? Is memory limited?
  2. Say the simple solution. Even if it is slow. “A loop inside a loop works. It is O(n²).”
  3. Find what is slow. Usually it is a repeated search. Ask: “Can a set, a dict, sorting or a heap remove this repeated work?”
  4. Write the better solution. Use clear names. Keep it small.
  5. Test it by hand. Walk through a small example. Then edge cases: empty input, one item, all items the same.
  6. Say the cost. Time and memory. And say what you would choose in a real project, and why.
Do not guess the cost from the number of lines. One short line can hide a loop: the in operator on a list, removing the first item of a list, or a database query inside a loop. Always ask: “What does this line do inside?”

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

  1. Big O tells you how the work grows when the data grows, not the exact time.
  2. A loop inside a loop is O(n²). Look for hidden loops, like the in operator on a list.
  3. A hash set or a dict finds a key in O(1) on average. Build it once, then look up many times.
  4. For order and ranges, use a sorted structure. Binary search is O(log n), but only on sorted data.
  5. Use the built-in sort, bisect, deque and heapq. They are fast and well tested.
  6. In an interview: ask, start simple, find the slow part, improve, test edge cases, and say the cost.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.