Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Algorithms & Competitive Programming — Alpha School

Lesson 4: Common Complexities and Choosing Data Structures

By now you can name the common complexities. The next step is to feel them: to know, without calculating, roughly how big an input each complexity can handle in a couple of seconds. As a rough guide for a typical contest, an O(n) algorithm can handle around a hundred million items, O(n log n) around ten million, O(n^2) around ten thousand, and O(2^n) only about twenty. These are worked-example figures, not measurements — the exact numbers depend on the machine and the language — but they explain why the input limits in a problem statement tell you which algorithm to aim for.

The same thinking applies to choosing a data structure, because the structure decides the cost of the operations you use most. A Python list gives fast access by index (O(1)) and fast appends, but inserting at the front or checking membership is O(n). A set gives membership tests and insertion in O(1) on average, but no ordering and no indexing. A dictionary gives O(1) lookups by key. A collections.deque gives fast appends and pops from both ends. And heapq gives you a priority queue, where the smallest item is always on top. The right choice is usually obvious once you ask which operation your algorithm repeats most often.

# Choosing the right structure changes the complexity.
nums = [5, 3, 5, 2, 3, 5, 1]

# Counting with a list: `list.count` scans the whole list each time — O(n^2) overall.
slow = {x: nums.count(x) for x in set(nums)}

# Counting with a dict: one pass, O(1) updates — O(n) overall.
from collections import Counter
fast = Counter(nums)
print(fast)  # Counter({5: 3, 3: 2, 2: 1, 1: 1})

# Membership: a set is O(1) on average; a list is O(n).
seen = set(nums)
print(3 in seen)  # True, fast even for a huge set

Reading limits like a contestant

Here is the working method. First, read the input limits. If n can be 10^5, you need O(n log n) or better — a quadratic solution will time out. If n is at most 20, an exponential solution that tries every subset might be the intended answer. If n is at most 100, O(n^3) is fine. Second, identify the operation your solution repeats most, and pick the data structure that makes it cheap. Third, write the simplest correct solution first, measure its complexity, and only then optimise. Many contest solutions start as a slow but correct version that clarifies the problem — and sometimes, when the limits are small, the slow version is the final answer.

One warning about Python specifically: it is slower than C++ by a large constant factor, so a Python solution needs a better complexity, or a smarter use of built-ins, to pass the same limits. That is not a reason to switch languages — it is a reason to lean on Python's strengths: dictionaries, sets, Counter, heapq, and the standard library, all of which run their heavy work in fast compiled code. The rest of this course builds the algorithms; this lesson's message is to always know what your tools cost.

Going further

There is a hard limit hiding behind the complexity table: any sorting algorithm that works only by comparing items cannot do better than O(n log n) in the worst case. The argument is a counting one — there are n! possible orders, and each comparison can only rule out half of them, so you need at least log2(n!) comparisons, which grows like n log n. That is why merge sort and quick sort are not just good sorts but essentially optimal for comparison-based sorting. The only way to beat the bound is to use more information than comparisons — for example, counting sort, which works when the values come from a small range.

The choice of data structure is also a choice about what your algorithm will spend its time doing. A problem that repeatedly asks for the smallest remaining item wants a heap; a problem that repeatedly asks whether something has been seen wants a set; a problem that repeatedly looks things up by name wants a dictionary. Before writing code, list the operations your solution will repeat most, and pick the structure that makes them cheap. That single question — what does this algorithm do most often? — is the fastest route to the right design.

Try applying the limits method to a problem you invent yourself: suppose you must find all pairs of numbers in a list that add up to a target, and the list can have up to a hundred thousand items. The pair-checking approach is O(n^2), which the limits rule out immediately — a hundred thousand squared is ten billion operations, far beyond a couple of seconds. The dictionary approach from Lesson 17, which checks each number's complement in O(1), is O(n) overall and fits easily. The limits told you the answer before you wrote a line of code, which is exactly what they are for.

Watch & Learn

One video to watch for this unit, from a trusted educator.

  • Algorithms in Python – Full Course for Beginners — freeCodeCamp.org
    Joy Brock's full course walks through recursion, data structures, divide and conquer, greedy algorithms and dynamic programming in Python — the whole map of this course in one video.

Key Terms

Data structure
A way of organising data — list, set, dict, deque, heap — each with different costs for its operations.
Counter
A dict subclass from collections that counts how often each item appears, in one pass.
deque
A double-ended queue from collections, with fast appends and pops from both ends.
heapq
The standard-library module providing a heap (priority queue) on top of a list.
Priority queue
A structure that always gives you the smallest (or largest) item first.
Membership test
Checking whether a value is present; O(1) on average in a set or dict, O(n) in a list.
Constant factor
The fixed speed difference between implementations; Big-O ignores it, but contests do not.

Discussion Questions

  1. If n can be 100,000, why is an O(n²) solution hopeless but an O(n log n) solution fine? Use the rough guide from the lesson.
  2. You need to check membership a million times. Why is a set the right choice, and what do you give up by using one instead of a list?
  3. When is the slow but correct solution the right final answer, rather than just a stepping stone?

Practice Questions

  1. Roughly how large an input can an O(n²) algorithm handle in a couple of seconds, per the lesson's guide?
  2. Why is counting with Counter faster than counting with list.count in a loop?
  3. Which structure gives O(1) average membership tests?
  4. n is at most 20 in a problem. Which complexity might be acceptable that would be hopeless for n = 100,000?
  5. What does heapq give you that a sorted list does not?
Show answers
  1. Around ten thousand items. These are worked-example figures, not measurements; the point is the order of magnitude.
  2. Counter makes one pass; list.count rescans the list for every distinct value. One pass is O(n); rescanning for each value is O(n²) overall.
  3. A set (or a dictionary, by key). Lists need a linear scan, which is O(n).
  4. O(2^n) — trying every subset. 2^20 is about a million, which is fine; 2^100000 is unimaginable.
  5. Fast access to the smallest item with cheap insertion. A heap keeps the minimum on top in O(log n) per insertion, while keeping a list sorted costs O(n) per insertion.
Keep reading to complete this lesson