Algorithms and complexity · Part 13 of 36

Big-O: how cost grows with input

Intermediate 15 min

Count steps instead of seconds, read O(1), O(log n), O(n), O(n log n) and O(n²), and pick the right data structure.

What you will learn

  • You can estimate the Big-O time of simple loops and nested loops.
  • You can rank the common complexity classes.
  • You can choose between a list, a set/hash map and a sorted array for lookups.

Before this: Lists, dictionaries and objects

Why not just time it?

Running time in seconds depends on the computer, the language and the moon phase. What you want to know is how the work grows when the input grows: if you double the number of plants in your database, does the search take twice as long, four times as long, or about the same?

Big-O notation describes that growth, ignoring constant factors and small inputs. O(n) means "grows at most in proportion to n" for large n.

Three paths up a hill: flat, steady slope and very steep

The common classes

Big-ONameExamplen = 1,000 → about
O(1)constantread list[5], look up a key in a hash map1 step
O(log n)logarithmicbinary search in a sorted array10 steps
O(n)linearfind the maximum of an unsorted list1,000 steps
O(n log n)linearithmicgood sorting (merge sort)10,000 steps
O(n²)quadraticcompare every pair1,000,000 steps
O(2ⁿ)exponentialtry every subsetmore than atoms in the universe

The jump from O(n log n) to O(n²) is the difference between "instant" and "a coffee break" at a million items.

Reading code

  • A single loop over n items: O(n).
  • A loop inside a loop, both over n: O(n²).
  • Halving the problem each round: O(log n).
  • Two loops one after the other: O(n) + O(n) = O(n) — constants drop out.
def has_duplicate_slow(items):        # O(n²)
    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            if items[i] == items[j]:
                return True
    return False

def has_duplicate_fast(items):        # O(n) on average
    seen = set()
    for x in items:
        if x in seen:
            return True
        seen.add(x)
    return False

The fast version trades memory (the set) for time — a very common trade.

Data structures decide

The same operation costs very different amounts depending on the structure:

OperationArray/listHash set/mapSorted arrayBalanced tree
look up by valueO(n)O(1) averageO(log n)O(log n)
insertO(1) at endO(1) averageO(n)O(log n)
keep in order—no orderyesyes

Python's dict/set and JavaScript's Map/Set are hash tables. Hidden O(n) operations are a classic performance bug: x in some_list or array.includes(x) inside a loop gives O(n²) overall.

Best, worst, average — and real life

Big-O usually describes the worst case. Quick sort is O(n²) in its worst case but O(n log n) on average, and fast in practice. For small n, constant factors win: a simple O(n²) insertion sort beats merge sort on ten items, which is why real sort functions switch to insertion sort for small pieces (Python's Timsort, used until 3.11, and Powersort since Python 3.11 both do this).

Try it: Sorting step by step

Watch five sorting algorithms compare and move items, and count their comparisons and writes.

Turn on JavaScript to use this lab. Worked example:

The sorting lab counts comparisons and swaps. With 8 random numbers, insertion sort needs up to 28 comparisons (n(n − 1)/2) in the worst case, merge sort at most 17.

Key points

  • Big-O describes how work grows with input size, ignoring constants.
  • O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ).
  • Nested loops over the input are typically O(n²); halving each step gives O(log n).
  • Hash sets/maps give O(1) average lookups; in on a list is O(n).
  • Worst case, average case and constant factors all matter in practice.

Flashcards

Question: What is the Big-O of binary search?
Answer: O(log n).
Question: What is the Big-O of two nested loops over the same n items?
Answer: O(n²).
Question: Why is x in some_list inside a loop often slow?
Answer: Each in-check is O(n), so the loop becomes O(n²).
Question: Which structures give O(1) average lookups?
Answer: Hash tables: Python dict/set, JavaScript Map/Set.

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. Order from slowest-growing to fastest-growing.

    Show the answer

    O(1) → O(log n) → O(n) → O(n log n) → O(n²)

    Constant < logarithmic < linear < linearithmic < quadratic.

    Source: CLRS ch. 3

  2. Binary search in a sorted list of 1,048,576 items needs about how many halving steps?

    Show the answer

    20 steps

    2²⁰ = 1,048,576, so log₂ n = 20.

    Source: MIT 6.006, Lecture 1

  3. What is the time complexity of has_duplicate_fast with a hash set?

    • O(n) on average
    • O(n²)
    • O(log n)
    • O(1)
    Show the answer

    O(n) on average

    One pass with O(1) average set operations: O(n).

    Source: CLRS ch. 11 Hash Tables

  4. A loop of n rounds calls array.includes(x) on an array of n items each round. Overall cost?

    • O(n²)
    • O(n)
    • O(log n)
    • O(n log n)
    Show the answer

    O(n²)

    includes is a linear scan, done n times.

    Source: MDN, Array.prototype.includes()

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.