Module 1 · Beginner · DSA foundations and complexity

Big-O notation in Python, with examples

Big-O notation explained with Python examples: O(1), O(log n), O(n), O(n log n), O(n²), Python's built-in costs, practice and interview questions.

By theprogrammers team · · updated · 6 min read

Big-O notation is how programmers talk about the speed of an algorithm without timing it on a particular computer. It answers one question: as the input gets bigger, how fast does the work grow?

It comes up in every coding interview, and more importantly, it helps you spot code that will be fine with 100 users and fall over with 100,000. This guide uses Python for every example and lists the cost of Python's built-in operations.

The idea in one example

Suppose you need to check whether a number is in a list:

def contains(items, target):
    for item in items:
        if item == target:
            return True
    return False

In the worst case, the target isn't there and the loop checks every item. With 10 items that is 10 checks; with a million items, a million checks. The work grows in a straight line with the input size n, so we say this function is O(n), "order n".

Big-O ignores the details that don't change the shape of the growth: how fast your laptop is, or whether each step takes 2 or 3 operations. It only keeps the part that dominates when n gets large.

The complexities you will meet most

Big-ONameExample1,000 items1,000,000 items
O(1)ConstantRead items[5]1 step1 step
O(log n)LogarithmicBinary search~10 steps~20 steps
O(n)LinearLoop over a list1,0001,000,000
O(n log n)LinearithmicGood sorting algorithms~10,000~20,000,000
O(n²)QuadraticCompare every pair1,000,0001,000,000,000,000

Look at the last row. An O(n²) algorithm that is instant on 1,000 items can take hours on a million. That is why complexity matters more than micro-optimisations.

O(1): constant time

The work doesn't depend on the input size at all:

def first(items):
    return items[0]

ages = {"ahana": 20, "rohan": 21}
ages["ahana"]          # dictionary lookup: O(1) on average

O(log n): halving the problem

Binary search on a sorted list throws away half the remaining items at every step:

def binary_search(items, target):
    low, high = 0, len(items) - 1
    while low <= high:
        mid = (low + high) // 2
        if items[mid] == target:
            return mid
        if items[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

A million items take only about 20 halvings to get down to one. Whenever you see a problem being cut in half each time, think O(log n).

O(n²): loops inside loops

Checking every pair of items needs a loop inside a loop:

def has_duplicate(items):
    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            if items[i] == items[j]:
                return True
    return False

For each of the n items, the inner loop runs up to n times, so roughly n × n steps. The same job can be done in O(n) with a set:

def has_duplicate(items):
    seen = set()
    for item in items:
        if item in seen:       # set lookup is O(1) on average
            return True
        seen.add(item)
    return False

This trade, using extra memory to avoid a nested loop, is one of the most common tricks in interviews.

How to work out the Big-O of your code

  1. Find the loops. A loop over the input is O(n). A loop inside it is O(n²).
  2. Look for halving. Repeatedly dividing the input is O(log n).
  3. Check the built-in calls. sorted() is O(n log n); x in some_list is O(n); x in some_set is O(1) on average.
  4. Keep the biggest term and drop constants. O(2n + 10) is just O(n); O(n² + n) is O(n²).

The cost of Python's built-in operations

Many slow programs have no visible nested loop: the hidden loop is inside a built-in operation. These are the costs to remember:

OperationBig-ONote
items[i], len(items)O(1)
items.append(x), items.pop()O(1)Amortised: occasionally the list grows, but on average it is O(1)
items.pop(0), items.insert(0, x)O(n)Every other item shifts; use collections.deque for O(1) at both ends
x in itemsO(n)Checks items one by one
sorted(items), items.sort()O(n log n)
d[key], key in d, s.add(x), x in sO(1) on averageDictionaries and sets use hashing
text += piece in a loopCan be O(n²)Strings can't be changed in place; "".join(pieces) is O(n)

Space complexity

Big-O also describes memory. The set version of has_duplicate is faster, but it stores up to n items, so it uses O(n) extra space, while the nested-loop version uses O(1). Interviewers often ask for both time and space.

Best, average and worst case

contains finishes after one step if the target is first (best case) but checks everything if it is missing (worst case). Big-O usually means the worst case, because that is what you need to plan for.

Practice

Work out the Big-O of each function, then open the answer.

  1. Summing a list:
def total(items):
    result = 0
    for x in items:
        result += x
    return result
Show the answer

O(n). One pass over the list, doing constant work per item.

  1. Doubling a counter:
def steps(n):
    count, i = 0, 1
    while i < n:
        i *= 2
        count += 1
    return count
Show the answer

O(log n). i doubles each time (1, 2, 4, 8…), so it reaches n after about log₂ n steps.

  1. Two loops, one after the other:
def min_and_max(items):
    smallest = min(items)
    largest = max(items)
    return smallest, largest
Show the answer

O(n). min and max each make one pass, so that is O(2n), and constants are dropped.

  1. Sorting, then one pass:
def closest_pair_gap(items):
    items = sorted(items)
    return min(b - a for a, b in zip(items, items[1:]))
Show the answer

O(n log n). Sorting costs O(n log n) and the pass after it costs O(n). The bigger term wins.

  1. Membership inside a loop:
def common(a, b):
    return [x for x in a if x in b]
Show the answer

O(n × m) when b is a list of m items, because each x in b scans b. Turn it into a set first, b = set(b), and it becomes O(n + m).

Interview questions

What does O(n) actually mean?

That the running time grows at most in proportion to the input size n, for large n. It is an upper bound on the growth rate, not an exact time. In interviews, Big-O usually means the worst case.

Why do we drop constants and smaller terms?

Big-O describes how the work grows as n gets large. At large n, O(2n + 10) behaves like O(n), and O(n² + n) like O(n²). Constants still matter in practice, but they don't change which algorithm scales better.

Why is list.append O(1) if the list sometimes has to grow?

Python over-allocates space, so growing (copying everything) happens rarely and the cost is spread over many appends. On average, called amortised, each append is O(1).

What is the space complexity of a recursive function?

Each call that hasn't returned yet takes space on the call stack, so recursion that goes n levels deep uses O(n) space, even if it creates no lists. That is also why very deep recursion in Python raises a RecursionError.

Is an O(n log n) algorithm always faster than an O(n²) one?

Not for small inputs: constants and overheads can make the O(n²) one faster on a few dozen items. That is why some sorting implementations switch to insertion sort for short runs. For large inputs, the O(n log n) algorithm always wins eventually.

What to learn next

  1. Go back to code you have written and label each function with its Big-O.
  2. See why speed at scale matters for whole applications in system design for beginners.
  3. Learn how NumPy makes O(n) work run far faster in practice.
  4. Practise Big-O on a classic technique: recursion explained, with Python examples.