Understanding how efficient your code is just by looking at it can be tricky. Thankfully, the brilliant minds before us have come up with a neat trick: Big O notation. This fancy little concept helps us measure how much time and space an algorithm will consume based on its input.
So, why should we care? Well, as engineers, our job boils down to two things: solving problems that have never been solved before, or solving problems that have been solved but in a more efficient way. Knowing Big O helps us make smarter decisions about which algorithms to use. It’s like having a cheat sheet for predicting how much time and memory your code will need, depending on the input size. Sounds good, right? Let’s break it down with a simple example: O(n), also known as linear time complexity.
O(n) — A Linear Approach
Take a look at this function:
const arr = [1, 3, 5, 5, 4, 6, 12, ...];
const addAllArrayElements = (arr) =>{
let sum = 0;
for(let i=0; i < arr.length; i++){
sum += arr[i];
}
return sum;
}
Here we have a simple function that takes an array of numbers and adds them all together. Now, let’s talk Big O. The for loop in this example runs once for each element in the array, which means the time taken grows directly with the size of the array. If there are n elements in the array, the function runs n times. Hence, we call this O(n)—linear time complexity.
Sure, you might point out that adding a value to the sum variable takes some time too. And you’re right! But in Big O terms, we ignore those small details (like constants) because they don’t significantly change how the function behaves as the input size grows.
Other Common Time Complexities
There are plenty of other important complexities you’ll encounter as you dive deeper into algorithms. Some of the most common include:
O(log n): This is usually seen in algorithms that divide the input in half at each step, like binary search.
O(n log n): You’ll often see this complexity in efficient sorting algorithms like Merge Sort or Quick Sort, where the input is divided into smaller chunks (log n) and then processed linearly (n).
Here's a quick reference to visualize the different complexities:
SOCIAL SHARE CARD GENERATOR