Time Complexity
Time complexity is just a fancy way of asking: "How much slower does my code get as the input grows?" It's not about counting exact seconds โ it's about the growth pattern. We use something called Big O notation to describe it.
Think of it like this. If you're making coffee for 1 person, it takes about the same effort as making coffee for 2 people โ O(1). But if you're seating guests at a dinner party, each new person adds more work โ O(n). That's time complexity in a nutshell.
We don't care about constants or small inputs. What matters is the trend. Does your code double in time when the input doubles? Or does it quadruple? That's the question Big O answers.
The Common Big O Classes
Here are the ones you'll encounter most often. O(1) is constant time โ same speed no matter what. O(log n) is logarithmic โ super efficient, like binary search. O(n) is linear โ you touch every element once. O(n log n) is what good sorting algorithms achieve. O(nยฒ) is nested loops โ gets ugly fast with large data.
Let's see them in action. The code below demonstrates linear search (O(n)) versus binary search (O(log n)). On a million elements, linear search might check all million. Binary search will check around 20. That's the power of understanding time complexity.
const arr = Array.from({ length: 1000000 }, (_, i) => i + 1);
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
console.log("Linear:", linearSearch(arr, 500000));
console.log("Binary:", binarySearch(arr, 500000));
Try it Yourself โ
How to Analyze Your Own Code
The trick is to look at loops. One loop over n elements? That's O(n). Two nested loops? O(nยฒ). A loop that cuts the problem in half each time? That's O(log n). You just count the "levels" of work your code does relative to the input size.
Don't stress about getting it perfect right away. Start by identifying the bottleneck in your code. Ask yourself: "If I 10x the input, what happens to the runtime?" That simple question will guide you a long way.