Big-O: How Fast Is My Code?

Data Structures & Algorithms · First Steps · Basics · 10 min

Measure code speed by counting steps as the input grows.

A square grid of boxes, n by n. O(1) lights one box, O(n) lights a single row, O(n²) lights the whole square. Make n bigger and watch the square explode while the row barely grows.

The idea in everyday words

Imagine finding a friend's name. O(1) = you already know their seat number. O(log n) = flipping a phone book in halves. O(n) = asking every person in a hall one by one. O(n²) = every person shaking hands with every other person. Big-O tells you how badly things slow down when the crowd gets bigger.

Why not just use seconds?

Your laptop and my laptop run at different speeds. So instead of seconds we count steps and ask: if the input doubles, how many more steps?

Big-O Name 1,000 items ≈ steps Feels like
O(1) constant 1 instant
O(log n) logarithmic 10 super fast
O(n) linear 1,000 fine
O(n log n) sort-like 10,000 ok
O(n²) quadratic 1,000,000 slow

Quick rules to find Big-O

  • One loop over n items → O(n)
  • A loop inside a loop → O(n²)
  • Cutting the problem in half each time → O(log n)
  • Drop constants: O(2n) is just O(n)
  • Keep the biggest term: O(n² + n) is O(n²)

Step by step

  1. Read the code:

    Find every loop.

  2. Single loop?:

    It touches each item once → O(n).

  3. Nested loop?:

    For every item you loop again → O(n × n) = O(n²).

  4. Halving?:

    Each step throws away half → O(log n).

  5. Simplify:

    Drop constants and small terms.

Code example

def has_duplicate_slow(nums):   # O(n^2)
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] == nums[j]:
                return True
    return False

def has_duplicate_fast(nums):   # O(n) using a set
    seen = set()
    for x in nums:
        if x in seen:
            return True
        seen.add(x)
    return False

print(has_duplicate_slow([1, 2, 3, 2]), has_duplicate_fast([1, 2, 3, 2]))

Complexity

  • Time: has_duplicate (in the Challenge tab): slow version O(n²) with two nested loops, fast version O(n) with a set
  • Space: slow version O(1), fast version O(n) because the set can grow to hold every number

Interview tips

  • Always state time AND space complexity after coding.

  • Trading memory for speed (using a set/map) is the most common optimisation.

  • Know: sorting is O(n log n), hash map lookup is O(1) on average.

Challenge: Find the Largest (in one pass)

Return the largest number in a non-empty list using a single loop: O(n). Don't use the built-in max or a sort.

Example: find_max([3, 9, 2]) → 9

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in First Steps

Previous: Classes & Objects · Next: Recursion