---
title: Time Complexity and Big O Notation Explained with Examples
url: https://www.masaischool.com/resources/time-complexity-and-big-o-explained
description: Time complexity and Big O notation in plain words: the common classes, how to work it out from loops and recursion, space complexity, and a Python step count.
updated: 2026-11-25
publisher: Masai (https://www.masaischool.com)
---

# Time Complexity and Big O Notation Explained: Classes, Rules, Space Complexity and a Step-Counting Demo

> **Short answer**
>
> Time complexity describes how the number of steps an algorithm takes grows as the input size n grows. Big O notation writes that growth rate while ignoring constants and smaller terms, so 3n + 5 steps is O(n). Common classes, fastest to slowest, are O(1), O(log n), O(n), O(n log n), O(n^2) and O(2^n). Space complexity measures extra memory the same way.

This page is for students starting DSA (data structures and algorithms), and for anyone who gets asked "what is the time complexity of your solution?" in a coding interview and wants a method, not a memorised list.

Every Python block was run on Python 3.9.6 on 25 November 2026 and the output shown is the real output. The demo counts steps instead of timing them, so you get the same numbers on any machine. Definitions were checked against the Wikipedia pages on Big O notation, binary search and sorting algorithms on the same date.

1. **Pick n** - what grows: items, digits, nodes
2. **Count the loops** - how often does the inner line run
3. **Keep the biggest term** - drop constants and small terms
4. **State the case** - worst case unless asked otherwise
A four-step method for stating the complexity of any piece of code.

## What time complexity and Big O notation mean

**Time complexity** is not the time in seconds. Seconds depend on the laptop, the language and what else is running. Time complexity counts basic steps (comparisons, additions, array reads) as a function of the input size, written **n**. If a loop over n items does 3 steps per item plus 5 steps of setup, the count is 3n + 5.

**Big O notation** keeps only the part of that count that matters when n is large. Drop the constant factor and the smaller terms, and 3n + 5 becomes O(n), read "order n" or "linear". Likewise 2n^2 + 40n + 7 is O(n^2), because once n is large the n^2 term dwarfs the rest. Formally, O gives an upper bound on growth.

Two related symbols appear in textbooks. **Big Omega** is a lower bound and **Big Theta** is a tight bound (both upper and lower). In interviews, people say "Big O" and usually mean the tight bound for the worst case. If you can state it as a tight bound, do.

Why it matters: complexity tells you whether a solution survives large input. The demo below shows an O(n^2) method doing about 8 million steps for 4,000 items where an O(n log n) method does about 26,000. It is the first thing asked after you write code in a [DSA interview](https://www.masaischool.com/resources/dsa-interview-questions).

## The common complexity classes

| Big O | Name | Steps when n = 1,000 | Typical example |
|---|---|---|---|
| O(1) | Constant | 1 | Read a[i], push to a stack, look up a key in a [hash map](https://www.masaischool.com/resources/hashmap-explained) (average case) |
| O(log n) | Logarithmic | About 10 | Binary search in a sorted array |
| O(n) | Linear | 1,000 | Find the maximum, linear search, one pass over a [linked list](https://www.masaischool.com/resources/linked-list-explained) |
| O(n log n) | Linearithmic | About 10,000 | Merge sort, and the best a comparison sort can do on average |
| O(n^2) | Quadratic | 1,000,000 | Compare every pair: bubble sort, a nested loop over the same array |
| O(2^n) | Exponential | A number with 302 digits | Try every subset, plain recursive Fibonacci |
| O(n!) | Factorial | Larger still | Try every ordering, such as brute-force travelling salesman |

The third column uses log base 2, and 2^10 = 1,024 is where "about 10" comes from. The base of the logarithm does not change the class, because changing base only multiplies by a constant. For graph algorithms you will also see two variables, as in O(V + E) for breadth-first search over V vertices and E edges, covered in [graph data structure explained](https://www.masaischool.com/resources/graph-data-structure-explained).

## How to work out time complexity from code

1. **Straight-line code is O(1).** A fixed number of statements, with no loop that depends on n, is constant time.
2. **A single loop over n items is O(n)**, as long as the loop body is O(1). Two loops one after the other are O(n) + O(n), which is still O(n).
3. **Nested loops multiply.** A loop of n inside a loop of n is O(n^2). If the inner loop runs over a different input of size m, it is O(n * m). An inner loop that starts at i + 1 still gives n(n - 1)/2 steps, which is O(n^2).
4. **Halving gives log n.** If each step throws away half of what is left (binary search, i = i * 2, walking down a balanced [tree](https://www.masaischool.com/resources/tree-data-structure-explained)), the loop runs about log2(n) times.
5. **A loop of n around a halving loop is O(n log n).** So is "split in half, solve both halves, combine in O(n)", the pattern of merge sort.
6. **For recursion, count the calls and the work per call.** One call per level with O(1) work is O(n), like factorial. Two calls per level on input n - 1 roughly doubles the work at each level, which is exponential.
7. **Check hidden loops.** In Python, x in my_list, my_list.index(x), slicing and sorted() are loops written by someone else. A line that looks O(1) may be O(n) or O(n log n).

### Halving in practice: binary searchdef binary_search_steps(n, target): lo, hi, steps = 0, n - 1, 0 while lo <= hi: steps += 1 mid = (lo + hi) // 2 if mid == target: return steps if mid < target: lo = mid + 1 # throw away the lower half else: hi = mid - 1 # throw away the upper half return steps for n in (1_000, 1_000_000, 1_000_000_000): print(n, "items ->", binary_search_steps(n, n - 1), "steps to find the last one")1000 items -> 10 steps to find the last one 1000000 items -> 20 steps to find the last one 1000000000 items -> 30 steps to find the last one

A thousand times more data costs 10 more steps. That is what O(log n) looks like, and why sorted data and balanced trees are so useful.

### Recursion: count the callsfrom functools import lru_cache calls = 0 def fib(n): # two recursive calls per call: exponential global calls calls += 1 return n if n < 2 else fib(n - 1) + fib(n - 2) memo_calls = 0 @lru_cache(maxsize=None) def fib_memo(n): # each n is computed once: O(n) time, O(n) space global memo_calls memo_calls += 1 return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2) for n in (10, 20, 25): calls = memo_calls = 0 fib_memo.cache_clear() fib_memo(n) print(n, fib(n), "plain calls:", calls, "memo calls:", memo_calls)10 55 plain calls: 177 memo calls: 11 20 6765 plain calls: 21891 memo calls: 21 25 75025 plain calls: 242785 memo calls: 26

Plain recursive Fibonacci makes 242,785 calls for n = 25 because it recomputes the same values again and again. Remembering each answer (memoisation) cuts that to 26 calls, O(n) time, at the cost of O(n) extra memory. This trade is the core of [dynamic programming](https://www.masaischool.com/resources/dynamic-programming-explained). For how recursive calls stack up, see [what is recursion](https://www.masaischool.com/resources/what-is-recursion).

## Demo: counting steps for O(n), O(n log n) and O(n^2)

This script counts the steps taken by three functions as n doubles: a single pass, a merge sort (counting comparisons) and a loop over every pair.def linear(n): # one pass: O(n) steps = 0 for _ in range(n): steps += 1 return steps def merge_sort_steps(a): # halve, sort both halves, merge: O(n log n) if len(a) <= 1: return a, 0 mid = len(a) // 2 left, s1 = merge_sort_steps(a[:mid]) right, s2 = merge_sort_steps(a[mid:]) out, i, j, steps = [], 0, 0, s1 + s2 while i < len(left) and j < len(right): steps += 1 # one comparison if left[i] <= right[j]: out.append(left[i]); i += 1 else: out.append(right[j]); j += 1 return out + left[i:] + right[j:], steps def all_pairs(n): # loop inside a loop: O(n^2) steps = 0 for i in range(n): for j in range(i + 1, n): steps += 1 return steps print(f"{'n':>6} {'O(n)':>8} {'O(n log n)':>11} {'O(n^2)':>10}") for n in (250, 500, 1000, 2000, 4000): worst_first = list(range(n, 0, -1)) data = worst_first[::2] + worst_first[1::2] # a fixed, unsorted input print(f"{n:>6} {linear(n):>8} {merge_sort_steps(data)[1]:>11} {all_pairs(n):>10}") n O(n) O(n log n) O(n^2) 250 250 1135 31125 500 500 2521 124750 1000 1000 5543 499500 2000 2000 12087 1999000 4000 4000 26175 7998000

Read the columns downwards. Each time n doubles:

- The **O(n)** column doubles: 250, 500, 1,000, 2,000, 4,000.
- The **O(n log n)** column slightly more than doubles: 5,543 to 12,087 is about 2.2 times.
- The **O(n^2)** column quadruples: 499,500 to 1,999,000 is about 4 times.

This doubling test works on any code. Run it at n and 2n, count steps or time it, and look at the ratio: about 2 means linear, about 4 means quadratic, about 8 means cubic. Notice too that the pair loop does n(n - 1)/2 steps, not n^2, and is still O(n^2): halving the count does not change how it grows.

## Best, average and worst case, and space complexity

The same algorithm can take different numbers of steps on different inputs of the same size. Linear search finds the target in 1 step if it is first (best case), n steps if it is last or missing (worst case) and about n/2 on average, which is still O(n). Unless the interviewer says otherwise, give the **worst case**, and mention the average when it differs.

| Algorithm | Best | Average | Worst | Extra space |
|---|---|---|---|---|
| Linear search | O(1) | O(n) | O(n) | O(1) |
| Binary search (iterative) | O(1) | O(log n) | O(log n) | O(1) |
| Bubble sort with early exit | O(n) | O(n^2) | O(n^2) | O(1) |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) |
| Quicksort | O(n log n) | O(n log n) | O(n^2) | O(log n) |

The sorting rows are explained, with code, in [sorting algorithms explained](https://www.masaischool.com/resources/sorting-algorithms-explained). A third idea, **amortised** cost, averages over a sequence of operations: appending to a Python list or a Java ArrayList is O(1) amortised, because the occasional O(n) resize is spread over many cheap appends.

### Space complexity

**Space complexity** is the extra memory an algorithm needs as n grows, written in the same notation. Count what you allocate beyond the input:

- A few variables, whatever the input size: O(1). Reversing an array in place by swapping ends is O(1) space.
- A new array, set or dictionary that can hold every item: O(n).
- An n by n grid, such as an adjacency matrix: O(n^2).
- **Recursion uses stack memory.** Each call that has not returned holds a stack frame, so recursion that goes n levels deep uses O(n) space even if it creates no arrays. A balanced divide-and-conquer recursion is O(log n) deep.

Time and space often trade against each other. A hash set makes "have I seen this value?" O(1) on average instead of O(n), and costs O(n) memory. Say both numbers when you present a solution: "O(n) time, O(n) space".

## Common mistakes in interviews

- **Treating Big O as speed.** O(n) is not always faster than O(n^2) for small n. Big O describes growth, and constants still matter in practice. This is why library sorts use insertion sort on short runs.
- **Counting loops instead of work.** Two nested loops are not automatically O(n^2). If the inner loop runs a fixed 26 times, or the two pointers together move at most n steps (sliding window), the total is O(n).
- **Forgetting library calls.** Sorting inside a loop, in on a list, string concatenation in a loop and slicing all cost more than O(1).
- **Ignoring the recursion stack** when stating space complexity.
- **Using one n for two inputs.** Merging lists of sizes n and m is O(n + m). Searching a grid of r rows and c columns is O(r * c).
- **Quoting hash map lookups as always O(1).** That is the average case. State it as "O(1) on average".
- **Stopping at the first working solution.** Say the brute-force complexity, then ask yourself what repeats. Sorting first, a hash map, two pointers or binary search often take a solution from O(n^2) to O(n log n) or O(n).

To practise, pick problems from the [data structures and algorithms path](https://www.masaischool.com/resources/data-structures-and-algorithms) and write the time and space complexity under every solution before you check the editorial. The [competitive programming roadmap](https://www.masaischool.com/resources/competitive-programming-roadmap) shows how contest limits on n hint at the complexity expected.

## Frequently asked questions

### What is time complexity in simple words?

Time complexity tells you how the number of steps an algorithm takes grows as its input gets bigger. It is written as a function of the input size n, such as O(n) or O(n^2). It is not a time in seconds, so it stays the same on a slow laptop and a fast server.

### What is Big O notation?

Big O notation describes the growth rate of an algorithm's running time or memory as the input size grows. You keep the fastest-growing term and drop constants, so 5n^2 + 3n + 2 is written O(n^2). It gives an upper bound and is normally quoted for the worst case.

### What is the difference between time complexity and space complexity?

Time complexity counts steps. Space complexity counts extra memory. Both are functions of the input size and use the same notation. Merge sort, for example, is O(n log n) time and O(n) extra space, while bubble sort is O(n^2) time and O(1) extra space.

### How do you calculate the time complexity of a program?

Decide what n is, then count how many times the innermost statement runs. A single loop is O(n), nested loops multiply, a loop that halves the input is O(log n), and recursion is the number of calls times the work per call. Keep the largest term and drop constants.

### Which time complexity is the best?

O(1), constant time, is the best because the work does not grow with the input. After that, in order: O(log n), O(n), O(n log n), O(n^2), O(2^n) and O(n!). For sorting by comparisons, O(n log n) is the best possible on average.

### Is O(n log n) better than O(n^2)?

Yes, for large inputs. In the step count on this page, at n = 4,000 the O(n log n) merge sort made 26,175 comparisons and the O(n^2) pair loop made 7,998,000 steps. For very small n the difference is negligible and a simple O(n^2) method can even win.

### What is the time complexity of binary search?

O(log n) in the worst and average case and O(1) in the best case, with O(1) extra space for the iterative version. Each comparison halves the search range, so a sorted array of one billion items needs at most about 30 comparisons. The array must be sorted first.

## Sources checked

- [Definition of Big O as an upper bound on growth; Omega and Theta; common orders](https://en.wikipedia.org/wiki/Big_O_notation)
- [Best, average, worst and memory figures for bubble sort, merge sort and quicksort; comparison sorts cannot beat O(n log n) on average](https://en.wikipedia.org/wiki/Sorting_algorithm)
- [Binary search O(log n) worst case, O(1) best case, O(1) space](https://en.wikipedia.org/wiki/Binary_search)
- [functools.lru_cache used for memoisation in the demo](https://docs.python.org/3/library/functools.html)
