Time complexity: O(n) vs O(log n)
What you'll learn: How to understand the massive speed difference between checking every item in a list versus splitting the list in half.
In computer science, we use "Big O" notation to describe how the runtime of an algorithm grows as the amount of data increases. When searching for a specific value in a collection, the two most common speeds you will encounter are O(n) and O(log n).
O(n): The Linear Scan
Imagine you are looking for a specific page in a messy pile of 100 loose papers. To be certain you find it, you might have to look at every single page, one by one. If you have 200 papers, it takes twice as long. If you have a million, it takes a million steps.
This is Linear Search. The time it takes is directly proportional to the number of items (). In C, this looks like a simple for loop:
// O(n) - We might check every element once
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) return i;
}
return -1;
}
O(log n): The Great Divide
Now, imagine you are looking for a name in a printed phone book. You don’t start at page one. You open to the middle. If the name starts with "M" and you are at "P," you throw away the entire second half of the book. You repeat this, cutting the remaining pages in half every time.
This is Binary Search, represented as O(log n). Because you eliminate half the data with every single step, it is incredibly efficient.
The Speed Gap
The difference between these two isn't just a little bit of time—it is transformative.
- For 1,000 items: O(n) takes 1,000 steps. O(log n) takes about 10 steps.
- For 1,000,000 items: O(n) takes 1,000,000 steps. O(log n) takes only about 20 steps.
While O(n) struggles as data grows, O(log n) barely breaks a sweat. However, there is a catch: to use the O(log n) approach, your data must be sorted beforehand.
Key takeaway
O(n) grows steadily with your data, while O(log n) stays lightning-fast even as your data grows to massive proportions.