N big o cheat sheet: the 5 complexities and how to spot each one in your code - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/big-o-cheat-sheet/
☷ big o cheat sheet: the 5 complexities and how to spot each one in your code - nicnonac guides _□×

← back to guides

big o cheat sheet: the 5 complexities and how to spot each one in your code

Stacks · 9 min read · posted Nov 30, 2026, 2:30 am

Most coding interviews end with someone asking for the time complexity of what you just wrote. Five answers cover nearly everything you'll write in one, and each has a shape you can spot in the code.

This is the cheat sheet from the reel. For each of the five you get the shape to look for, the Python from the reel with its step count, and what happens when the input doubles. After that there's a way to work out the complexity of your own solution, and the tables worth memorising.

Every count below came from running the code on the same 8 numbers, [7, 4, 9, 2, 8, 5, 1, 6], and then on 16.

what big o measures

Big O says how the number of steps grows as the input grows. It isn't a time in seconds. It answers one question: if the input gets twice as big, what happens to the work?

n is the size of the input, usually the length of the list. Constants and smaller terms are dropped, so 2n + 5 steps is O(n), and n² + n steps is O(n²). Unless you're asked otherwise, give the worst case.

the quick lookup

you see in the code it's probably double the input and the work
no loop over the input: an index, a dict lookup, a push or a pop O(1) stays the same
a loop that halves what's left each time O(log n) goes up by one step
one loop over the input O(n) doubles
a sort, or split in half and do one pass per level O(n log n) a bit more than doubles
a loop inside a loop, both over the input O(n²) goes up four times

the five on the same numbers

complexity steps at n = 8 steps at n = 16 one step is
O(1) 1 1 one read of the list
O(log n) 4 5 one pass of the loop
O(n) 8 16 one comparison
O(n log n) 24 64 one item merged
O(n²) 64 256 one comparison

At 8 items they all look fine. This is what the same five do at real sizes:

n log n n log n n²
1,000 about 10 about 10,000 1,000,000
1,000,000 about 20 about 20,000,000 1,000,000,000,000

1. O(1), constant

Spot it. No loop that depends on the input. Reading nums[i], looking up a key in a dict, checking x in some_set, pushing or popping the end of a list.

def get_item(nums, i):
    return nums[i]

nums = [7, 4, 9, 2, 8, 5, 1, 6]
print(get_item(nums, 4))

In the reel this reads index 4 and gets 8, in one step. With 16 numbers, or 16 million, it's still one step.

What catches people. O(1) doesn't mean fast. It means the cost doesn't grow. And x in my_list is not O(1): it walks the list, so it's O(n). The same check on a set or a dict is O(1) on average.

2. O(log n), logarithmic

Spot it. The code throws away half of what's left on every step. Binary search is the standard one. So is any loop where the counter doubles or halves, i *= 2 or n //= 2, and one walk down a balanced tree.

def search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

In the reel the target is 9, the last of the 8 sorted numbers, which is the worst case. The part left to search goes 8, 4, 2, 1, so it takes 4 passes. With 16 numbers it takes 5. Doubling the input adds one step, which is why a million items need only about 20.

What catches people. Binary search needs sorted input. If you have to sort first, the sort costs O(n log n), and that's the number that counts.

3. O(n), linear

Spot it. One loop over the input, doing a fixed amount of work each time round. Finding the max, summing, counting, one pass with a hash map.

def find_max(nums):
    best = nums[0]
    for x in nums:
        if x > best:
            best = x
    return best

8 numbers, 8 comparisons. 16 numbers, 16 comparisons.

Two loops one after the other are still O(n). That's n + n = 2n steps, and the 2 is dropped.

What catches people. Hidden loops. max(nums), sum(nums), nums.index(x), x in nums, a slice like nums[1:] and nums.pop(0) each walk the list. Put one of those inside a loop and you've written O(n²) without a second for in sight.

4. O(n log n), linearithmic

Spot it. A sort. Or divide and conquer: split the input in half, solve each half, then do one pass to join them.

def merge_sort(a):
    if len(a) <= 1:
        return a
    m = len(a) // 2
    l = merge_sort(a[:m])
    r = merge_sort(a[m:])
    out = []
    while l and r:
        if l[-1] > r[-1]:
            out.append(l.pop())
        else:
            out.append(r.pop())
    return l + r + out[::-1]

This is the version in the reel. It merges from the big end of each half with pop(), which is O(1), so each merge is a single pass. 8 numbers split down to single items in 3 levels, and every level merges all 8 items, so 3 × 8 = 24 steps. 16 numbers have 4 levels, so 4 × 16 = 64. That's log n levels with n work on each.

Python's sorted() and list.sort() are O(n log n) too. If your solution sorts and then does one pass, the whole thing is O(n log n).

What catches people. Forgetting the sort. "I sort, then use two pointers, so it's O(n)" is the common slip. The two pointers are O(n), but the sort in front of them is O(n log n), and the bigger one wins.

5. O(n²), quadratic

Spot it. A loop inside a loop, both over the input. Comparing every item with every other item. It's what the brute-force answer usually looks like.

def smaller_counts(nums):
    out = []
    for x in nums:
        count = 0
        for y in nums:
            if y < x:
                count += 1
        out.append(count)
    return out

For each number it counts how many of the others are smaller, by checking it against all 8. That's 8 × 8 = 64 comparisons. With 16 numbers it's 256. Double the input and the work goes up four times.

It's fine for small inputs, and it's often the right first answer to say out loud. The follow-up is nearly always "can you do better". The usual ways down are a hash map, which gets you to O(n), or sorting first, which gets you to O(n log n). Here sorting does it:

def smaller_counts(nums):
    first = {}
    for i, x in enumerate(sorted(nums)):
        first.setdefault(x, i)      # how many numbers sort before x
    return [first[x] for x in nums]

What catches people. Not every nested loop is O(n²). If the inner loop runs a fixed number of times, say over the 26 letters, the whole thing is O(n). And when two pointers only ever move forward, like a sliding window, the inner while adds up to n steps across the whole run, so that's O(n) too.

how to work it out for your own solution

  1. Name n. Say what it is: the length of the list, the number of nodes, the number of characters.
  2. Find the loops that depend on n. One after another, add them. One inside another, multiply them.
  3. Check each line inside a loop for hidden work: a slice, an in on a list, a sort.
  4. A loop that halves is log n. Recursion that splits in two and does one pass per level is n log n.
  5. Keep the biggest term and drop the constants.
  6. Then give the space: the extra memory you allocate, not counting the input. A hash map of everything is O(n). A few variables is O(1). Recursion uses stack space as deep as it goes.

Two different inputs get two letters. Walking a grid is O(rows × cols). Visiting a whole graph is O(V + E), the nodes plus the edges.

the tables worth memorising

Python operations.

operation cost
nums[i], nums.append(x), nums.pop() O(1)
nums.insert(0, x), nums.pop(0), x in nums O(n)
nums[a:b] O(k), the length of the slice
dict or set: get, set, delete, in O(1) on average
deque: append or pop at either end O(1)
heapq.heappush, heapq.heappop O(log n)
heap[0], reading the smallest O(1)
sorted(nums), nums.sort() O(n log n)

Sorts.

sort average worst extra space
merge sort O(n log n) O(n log n) O(n)
quicksort O(n log n) O(n²) O(log n)
heapsort O(n log n) O(n log n) O(1)
insertion sort O(n²) O(n²) O(1)
Python's sorted (Timsort) O(n log n) O(n log n) O(n)

Interview algorithms.

algorithm time
binary search O(log n)
two pointers, sliding window O(n)
one pass with a hash map O(n)
BFS or DFS on a graph O(V + E)
BFS or DFS on a grid O(rows × cols)
keeping a heap of size k over n items O(n log k)
generating all subsets O(n × 2^n)
generating all permutations O(n × n!)

how to practise with this

After every problem you solve, say the time and space complexity out loud before you check it. Then check it. It takes ten seconds, and it's the same question you'll get in the room.

When the interviewer asks "can you do better", read the quick lookup backwards. You're at O(n²), so is there a hash map that gets it to O(n), or a sort that gets it to O(n log n)?

honest limitations

Five isn't the whole list. O(2^n) and O(n!) turn up with backtracking, and O(V + E) with graphs.

Big O ignores constants. It can't tell you which of two O(n) solutions is faster, and on small inputs a plain O(n²) loop can beat a clever O(n log n) one.

The step counts here count one thing per algorithm: comparisons, loop passes or items merged. Count a different thing and the numbers change. The growth doesn't, and the growth is what Big O describes.

Hash map costs are averages. The worst case for a dict lookup is O(n), and interviewers accept O(1) as long as you say "on average".

The patterns these complexities come from are in the coding interview cheat sheet, and what each structure costs is in the data structures cheat sheet.

← all guides

Done nicnonac.com 56.6k