Big-O introduction

Big O Notation

The problem it solves

You write code. It works. But does it still work when you have 1 million pieces of data instead of 10? Big O is a way to answer that question without running the code and waiting to find out.

The core idea

Big O counts how many "steps" your code takes as the amount of data grows. It doesn't care about seconds or your computer's speed. It only cares about the pattern.

Three patterns, explained with a phone book

  1. O(1) — Constant You know the exact page number. You flip straight to it. Doesn't matter if the phone book has 10 pages or 10,000 pages, it takes one flip. Example: looking up a value using its exact index in a list.

  2. O(n) — Linear You don't know the page. You start at page 1 and check every single page until you find the name. A phone book twice as long takes twice as long to search. Example: scanning through a list one item at a time to find the biggest number.

  3. O(n²) — Quadratic For every single name in the phone book, you check it against every other name in the phone book. A phone book twice as long doesn't take twice as long. It takes four times as long, because now you're doing "twice the work" for "twice the entries." Example: comparing every item in a list to every other item (nested loops).

Why this matters — the scary chart

Items O(n) time O(n²) time
1,000 instant instant
10,000 instant noticeably slow
1,000,000 a few seconds could take years

That's the whole point of Big O. O(n) stays manageable. O(n²) becomes unusable once data gets big, even though both looked "fine" on small test data.

The one rule to remember

If you see a loop inside a loop, both going over the same data, that's usually O(n²), and it's a warning sign for anything that needs to handle large amounts of data.