Your code works. Great! But here’s a question every programmer runs into sooner or later: will it still work when your 10 users turn into 10 million? Or when that list of 100 items turns into 100,000?
That’s the problem Big O notation was made to solve. It’s one of those topics that sounds scary the first time you hear it, with its strange O(n²) symbols and talk of “complexity”. But the core idea is surprisingly simple, and by the end of this guide you’ll be able to look at a piece of code and say roughly how it will behave as the input grows. We’ll cover what Big O is, the most common time complexities, how to work them out with simple rules, and a handy Big O cheat sheet, all with Python examples.
What Is Big O Notation?
Big O notation describes how the amount of work an algorithm does grows as its input gets bigger. That’s it. It doesn’t tell you how many seconds your code takes, because that depends on your computer, your programming language and a dozen other things. Instead, it answers a more useful question: if I double the input, what happens to the work?
Think of it like a road trip. Saying “the trip takes 3 hours” depends on traffic and your car. But saying “every extra 100 kilometers adds about an hour” tells you how the trip scales, no matter which car you drive. Big O is that second kind of statement.
In practice, when people say an algorithm is O(n), they usually mean this describes its worst case: an upper limit on how much the work can grow. The letter n stands for the size of the input, like the number of items in a list.
Why Does Big O Matter?
- Your code will meet bigger data. An approach that feels instant on 100 items can freeze on 1,000,000.
- It helps you choose. Should you store things in a list or a set? Use bubble sort or merge sort? Big O gives you a fair way to compare.
- It’s a coding interview staple. Interviewers love asking, “What’s the time complexity of your solution?”
The Most Common Big O Complexities
Let’s walk through the ones you’ll see again and again, from fastest to slowest.
O(1): Constant time
The work stays the same no matter how big the input is. Grabbing the first item from a list takes one step whether the list has 10 items or 10 million.
def get_first(items):
return items[0] # one step, alwaysO(log n): Logarithmic time
The work grows very slowly, because each step cuts the problem in half. It’s like looking up a name in a paper phone book: you open it in the middle, decide whether your name comes before or after, and throw away half the book. Repeat. The classic example is binary search on a sorted list.
def binary_search(items, target): # items must be sorted
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1For a sorted list of 1,000,000 items, this needs at most about 20 steps. That’s the magic of logarithms.
O(n): Linear time
The work grows in direct proportion to the input. Double the list, double the work. Searching for something in an unsorted list means checking items one by one, which is the typical example.
def linear_search(items, target):
for i, value in enumerate(items):
if value == target:
return i
return -1O(n log n): Linearithmic time
A little slower than linear, but still very good. This is the sweet spot for efficient sorting. Merge sort and heap sort are O(n log n) in every case, and quick sort is O(n log n) on average.
O(n²): Quadratic time
The work grows with the square of the input. The easiest picture is a room of people where everyone shakes hands with everyone else. With 10 people, that’s 45 handshakes. With 100 people, it’s 4,950. The usual culprit in code is a loop inside another loop, like checking every pair of items for duplicates:
def has_duplicate_slow(items):
for i in range(len(items)):
for j in range(i + 1, len(items)):
if items[i] == items[j]:
return True
return FalseOn 1,000 distinct items, this makes 499,500 comparisons. Simple sorts like bubble sort, selection sort and insertion sort are also O(n²) in their worst cases.
The good news is that quadratic code can often be rewritten. Using a set to remember what you’ve already seen turns that duplicate check into O(n) on average:
def has_duplicate_fast(items):
seen = set()
for x in items:
if x in seen: # set lookups are O(1) on average
return True
seen.add(x)
return FalseO(2ⁿ) and O(n!): Exponential and factorial time
These are the danger zone. With O(2ⁿ), the work doubles every time you add one more item. Generating every possible subset of a list is a good example, since a list of n items has 2ⁿ subsets. With O(n!), the work grows even faster. Trying every possible ordering of items, like brute-forcing the travelling salesman problem, is the classic case. Both are fine for tiny inputs and hopeless for big ones.
Big O Growth Explorer
Drag the slider to change the input size (n) and see how many steps each type of algorithm needs. The bars use a log scale so every row stays visible.
Big O Cheat Sheet
Here’s a quick reference you can bookmark. The last column shows roughly how many steps each one takes when n = 1,000.
| Name | Notation | Typical example | Steps at n = 1,000 |
|---|---|---|---|
| Constant | O(1) | Get an item by index | 1 |
| Logarithmic | O(log n) | Binary search | about 10 |
| Linear | O(n) | Loop through a list | 1,000 |
| Linearithmic | O(n log n) | Merge sort, heap sort | about 10,000 |
| Quadratic | O(n²) | Nested loops, bubble sort | 1,000,000 |
| Exponential | O(2ⁿ) | All subsets of a list | a number with more than 300 digits |
| Factorial | O(n!) | All orderings (permutations) | even bigger |
How to Calculate Big O: 4 Simple Rules
You don’t need heavy math to work out the Big O of most code. These four rules will take you a long way.
Rule 1: Drop the constants
Big O cares about the shape of the growth, not the exact count. A loop that does 2 steps per item, or 5, is still O(n). So O(2n) becomes O(n).
Rule 2: Keep only the biggest term
When the input is huge, the fastest-growing part wins. So O(n² + n) becomes O(n²), and O(n + 1) becomes O(n).
def example(items):
print(items[0]) # O(1)
for x in items: # O(n)
print(x)
for a in items: # O(n²)
for b in items:
print(a, b)
# Total: O(1 + n + n²), which simplifies to O(n²)Rule 3: Steps in a row add, steps inside each other multiply
Two loops one after the other add up, which gives O(n + n) = O(n). A loop nested inside another multiplies, which gives O(n × n) = O(n²).
Rule 4: Different inputs get different letters
If a function loops over one list and then another, those lists can be different sizes, so call them a and b. Two loops in a row are O(a + b). A loop nested inside another is O(a × b). Don’t call both n unless they truly are the same size.
Best, Average and Worst Case
The same algorithm can behave differently depending on the input. In a linear search, you might find the item immediately (best case, O(1)), or you might have to check every item (worst case, O(n)). Big O usually talks about the worst case, because it gives you a guarantee. Some algorithms have an average case that differs from the worst case. Quick sort is a good example: O(n log n) on average, but O(n²) in the worst case.
You may also run into two cousins of Big O. Big Omega (Ω) describes a lower bound, and Big Theta (Θ) describes a tight bound, where the upper and lower bounds match. For everyday programming and interviews, Big O is the one you need.
What About Space Complexity?
Big O isn’t just about time. Space complexity uses the same notation to describe how much extra memory an algorithm needs as the input grows. Making a new list with one entry per input item uses O(n) space. Swapping a couple of values inside the existing list uses O(1). This is exactly why merge sort needs extra O(n) memory, while heap sort sorts in place with O(1).
Big O of Sorting Algorithms
Here’s how the sorting algorithms we’ve covered in this series compare:
| Algorithm | Best | Average | Worst | Extra space |
|---|---|---|---|---|
| Bubble sort | O(n) | O(n²) | O(n²) | O(1) |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) |
| Quick sort | O(n log n) | O(n log n) | O(n²) | O(log n) average |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | O(1) |
Big O of Common Python Operations
Knowing the cost of everyday operations helps you avoid sneaky slowdowns. Here are some of the most useful ones in Python:
| Operation | Complexity |
|---|---|
my_list[i] (get by index) | O(1) |
my_list.append(x) | O(1) amortized |
len(my_list) | O(1) |
my_list.insert(0, x) or my_list.pop(0) | O(n) |
x in my_list | O(n) |
x in my_set or x in my_dict | O(1) on average |
sorted(my_list) or my_list.sort() | O(n log n) |
A classic trap: using x in my_list inside a loop. Each check is O(n), so the whole thing quietly becomes O(n²). Switching the list to a set is often the one-line fix.
Common Mistakes Beginners Make
- Thinking Big O measures seconds. It measures how the work grows, not how long it takes on your laptop.
- Assuming two loops always means O(n²). Loops one after another are
O(n). Only nested loops over the input multiply. - Forgetting that a nested loop can be cheap. If the inner loop always runs a fixed number of times, like 10, the total is still
O(n). - Ignoring hidden costs. Operations like
inon a list, slicing, or copying a list are not free. Each one hides a loop. - Treating a “better” Big O as always faster. On tiny inputs, a simple
O(n²)approach can beat a fancyO(n log n)one, which is why some real sorting routines use insertion sort for small pieces.
Quick Practice: Test Yourself
What’s the time complexity of each of these? Try them before checking the answers below.
for x in items: print(x)return items[len(items) // 2]- A loop over
itemswith another loop overitemsinside it. - A loop that cuts the remaining items in half on every pass.
- A loop over
itemswith an innerfor _ in range(10)loop.
Answers: (1) O(n). (2) O(1), since finding the middle index and reading it takes the same time however long the list is. (3) O(n²). (4) O(log n). (5) O(n), because the inner loop is a fixed 10 steps, which Rule 1 says to drop.
Quick Recap
Big O notation describes how an algorithm’s work (or memory) grows as the input grows. Remember the ladder from best to worst: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ), O(n!). To work it out, drop constants, keep the biggest term, add steps in a row, and multiply steps inside each other. Once that clicks, comparing algorithms becomes much easier, and the sorting guides in this series will make a lot more sense.
Frequently Asked Questions
What is Big O notation in simple words?
It’s a way to describe how much slower (or more memory-hungry) an algorithm gets as its input grows, without worrying about the exact speed of any particular computer.
What does O(n) mean?
It means the work grows in direct proportion to the input size. If you double the number of items, the work roughly doubles.
What is the difference between O(n) and O(log n)?
With O(n), you may have to look at every item. With O(log n), each step throws away half of what’s left, so even a million items need only about 20 steps, like binary search on a sorted list.
Why do we drop constants in Big O?
Because Big O describes the shape of growth for large inputs. Whether a loop takes 2 steps or 5 steps per item, doubling the input still roughly doubles the work, so both are O(n).
What is the best time complexity?
O(1), constant time, is the best, because the work doesn’t grow with the input at all. O(log n) comes close.
Is O(n log n) good?
Yes. It’s the best you can do for general-purpose comparison sorting, and it’s what merge sort, heap sort and quick sort (on average) deliver.
How do I learn Big O faster?
Practice on real code. Take any function you’ve written, count the loops, and apply the four rules above. Then read about sorting algorithms like bubble sort and merge sort, which show quadratic and linearithmic growth in action.
Found this helpful? Open the Growth Explorer above and push the slider to 30. Watching O(2ⁿ) explode is the quickest way to feel why Big O matters.
