There are many kinds of algorithms. Most of them fall into one of the eight-time complexities that we will explore in this chapter.
-
Constant time: O(1)
-
Logarithmic time: O(log n)
-
Linear time: O(n)
-
Linearithmic time: O(n log n)
-
Quadratic time: O(n2)
-
Cubic time: O(n3)
-
Exponential time: O(2n)
-
Factorial time: O(n!)
We are going to provide examples for each one of them.
Before we dive in, here’s a plot with all of them.
The above chart shows how the algorithm’s running time is related to the CPU’s work. As you can see, O(1) and O(log n) is very scalable. However, O(n2) and worst can convert your CPU into a furnace 🔥 for massive inputs.
Represented as O(1), it means that regardless of the input size, the number of operations executed is always the same. Let’s see an example:
Let’s implement a function that finds out if an array is empty or not.
link:../../../src/runtimes/01-is-empty.js[role=include]
Another more real life example is adding an element to the begining of a part02-linear-data-structures.asc. You can check out the implementation here.
As you can see in both examples (array and linked list), if the input is a collection of 10 elements or 10M, it would take the same amount of time to execute. You can’t get any more performant than this!
Represented in Big O notation as O(log n), when an algorithm has this running time, it means that as the input size grows, the number of operations grows very slowly. Logarithmic algorithms are very scalable. One example is the binary search.
The binary search only works for sorted lists. It starts searching for an element in the middle of the array, and then it moves to the right or left depending on if the value you are looking for is bigger or smaller.
link:../../../src/runtimes/02-binary-search.js[role=include]
This binary search implementation is a recursive algorithm, which means that the function binarySearchRecursive
calls itself multiple times until the program finds a solution. The binary search splits the array in half every time.
Finding the runtime of recursive algorithms is not very obvious sometimes. It requires some approaches like recursion trees or the Master Theorem.
Since the binarySearch
divides the input in half each time. As a rule of thumb, when you have an algorithm that divides the data in half on each call, you are most likely in front of a logarithmic runtime: O(log n).
Linear algorithms are one of the most common runtimes. Their Big O representation is O(n). Usually, an algorithm has a linear running time when it visits every input element a fixed number of times.
Let’s say that we want to find duplicate elements in an array. What’s the first implementation that comes to mind? Check out this implementation:
link:../../../src/runtimes/03-has-duplicates.js[role=include]
hasDuplicates
has multiple scenarios:-
Best-case scenario: the first two elements are duplicates. It only has to visit two elements and return.
-
Worst-case scenario: no duplicates or duplicates are the last two. In either case, it has to visit every item in the array.
-
Average-case scenario: duplicates are somewhere in the middle of the collection.
As we learned before, the big O cares about the worst-case scenario, where we would have to visit every element on the array. So, we have an O(n) runtime.
Space complexity is also O(n) since we are using an auxiliary data structure. We have a map that, in the worst case (no duplicates), it will hold every word.
You can represent linearithmic algorithms as O(n log n). This one is important because it is the best runtime for sorting! Let’s see the merge-sort.
The Merge Sort, like its name indicates, has two functions merge and sort. Let’s start with the sort function:
link:../../../src/algorithms/sorting/merge-sort.js[role=include]
-
If the array only has two elements, we can sort them manually.
-
We divide the array into two halves.
-
Merge the two parts recursively with the
merge
function explained below
link:../../../src/algorithms/sorting/merge-sort.js[role=include]
The merge function combines two sorted arrays in ascending order. Let’s say that we want to sort the array [9, 2, 5, 1, 7, 6]
. In the following illustration, you can see what each function does.
How do we obtain the running time of the merge sort algorithm? The merge-sort divides the array in half each time in the split phase, log n, and the merge function join each splits, n. The total work is O(n log n). There are more formal ways to reach this runtime, like using the Master Method and recursion trees.
Quadratic running times, O(n2), are the ones to watch out for. They usually don’t scale well when they have a large amount of data to process.
Usually, they have double-nested loops, where each one visits all or most elements in the input. One example of this is a naïve implementation to find duplicate words on an array.
If you remember, we have solved this problem more efficiently in the Linear section. We solved this problem before using an O(n), let’s solve it this time with an O(n2):
link:../../../src/runtimes/05-has-duplicates-naive.js[role=include]
As you can see, we have two nested loops causing the running time to be quadratic. How much difference is there between a linear vs. quadratic algorithm?
Let’s say you want to find a duplicated middle name in a phone directory book of a city of ~1 million people. If you use this quadratic solution, you would have to wait for ~12 days to get an answer 🐢; while if you use the linear solution, you will get the answer in seconds! 🚀
Cubic O(n3) and higher polynomial functions usually involve many nested loops. An example of a cubic algorithm is a multi-variable equation solver (using brute force) or finding three elements on an array that add up to a given number.
Let’s say you want to find 3 items in an array that add up to a target number. One brute force solution would be to visit every possible combination of 3 elements and add them to see if they are equal to the target.
function threeSum(nums, target = 0) {
const ans = [];
for(let i = 0; i < nums.length -2; i++)
for(let j = i + 1; j < nums.length - 1; j++)
for(let k = j + 1; k < nums.length; k++)
if (nums[i] + nums[j] + nums[k] === target)
ans.push([nums[i], nums[j], nums[k]]);
return ans;
}
As you can see, three nested loops usually translate to O(n3). If we had four nested loops (4sum), it would be O(n4) and so on. A runtime in the form of O(nc), where c > 1, we refer to this as a polynomial runtime.
Note
|
You can improve the runtime of 3sum from O(n3) to O(n2), if we sort items first and then use one loop and two pointers to find the solutions. |
Exponential runtimes, O(2n), means that every time the input grows by one, the number of operations doubles. Exponential programs are only usable for a tiny number of elements (<100); otherwise, it might not finish in your lifetime. 💀
Let’s do an example.
Finding all distinct subsets of a given set can be implemented as follows:
link:../../../src/runtimes/07-sub-sets.js[role=include]
-
Base case is empty element.
-
For each element from the input, append it to the results array.
-
The new results array will be what it was before + the duplicated with the appended element.
Every time the input grows by one, the resulting array doubles. That’s why it has an O(2n).
The factorial runtime, O(n!)
, is not scalable at all. Even with input sizes of ~10 elements, it will take a couple of seconds to compute. It’s that slow! 🍯🐝
A factorial is the multiplication of all the numbers less than itself down to 1.
-
3! = 3 x 2 x 1 = 6
-
5! = 5 x 4 x 3 x 2 x 1 = 120
-
10! = 3,628,800
-
11! = 39,916,800
One classic example of an O(n!) algorithm is finding all the different words formed with a given set of letters.
link:../../../src/runtimes/08-permutations.js[role=include]
As you can see in the getPermutations
function, the resulting array is the factorial of the word length.
Factorial starts very slow and quickly becomes unmanageable. A word size of just 11 characters would take a couple of hours in most computers! 🤯
We went through 8 of the most common time complexities and provided examples for each of them. Hopefully, this will give you a toolbox to analyze algorithms.
Big O Notation | Name | example (s) |
---|---|---|
O(1) |
||
O(log n) |
||
O(n) |
||
O(n log n) |
||
O(n2) |
||
O(n3) |
||
O(2n) |
||
O(n!) |