Fundamentals7 min readLast updated: Fri Mar 15 2024 00:00:00 GMT+0000 (Coordinated Universal Time)

Big O Notation Explained Simply

In programming, "it works" is not enough. We need to know how fast it works as the data grows. This is Time Complexity, measured using Big O Notation.

The Analogy: The Phone Book

Imagine you need to find a name in a phone book containing 1,000,000 names.

O(n) - Linear Time

Method: You start at the first page and read every single name until you find the one you want.

  • Best Case: It's the first name (1 step).
  • Worst Case: It's the last name (1,000,000 steps).
  • Average: 500,000 steps.

If the book doubles in size, the time doubles. This is O(n).

O(log n) - Logarithmic Time

Method: You open the book to the middle.

  • Is the name before or after this page?
  • Before: You rip out the second half of the book.
  • After: You rip out the first half.
  • Repeat with the remaining half.

With 1,000,000 names, you only need 20 steps to find any name.
If the book doubles (2,000,000 names), you only need 21 steps.
This is Binary Search, or O(log n). It is incredibly fast.

O(1) - Constant Time

Method: You have a magic index. You know exactly what page the name is on.

  • You open directly to page 452.
  • Time: 1 step.

It doesn't matter if the book has 10 names or 10 billion. It takes the same amount of time. This is how Hash Maps (Dictionaries/Objects) work.

Summary Chart

Notation Name Speed Example
O(1) Constant Instant Array Index Access arr[5]
O(log n) Logarithmic Very Fast Binary Search
O(n) Linear OK Loop through list
O(n²) Quadratic Slow Nested Loops (Bubble Sort)