Big O Notation - Time Complexity Explained With Real Code
1) Constant Time - O(1)
The work stays the same no matter how large the input grows.
2) Logarithmic Time - O(log n)
Each step throws away a constant fraction of the remaining input, usually half.
3) Linear Time - O(n)
The work grows in direct proportion to the size of the input.
4) Square Root Time - O(√n)
The work grows with the square root of the input, which shows up when you only need to check up to √n.
5) Loglinear Time - O(n log n)
Linear work repeated a logarithmic number of times, which is the cost of most efficient sorts.
6) Two Inputs - O(n * m)
Two independent inputs of sizes n and m, where every element of the first input is paired with every element of the second input.
7) Quadratic Time - O(n²)
The work grows with the square of the input size.
This usually comes from comparing every element with every other element of the same input. Two loops written one after the other are O(n) + O(n), which is still O(n).
8) Cubic Time - O(n³)
The work grows with the cube of the input size, typically from three nested loops over the same input.
9) Exponential Time - O(2ⁿ)
The work doubles every time the input grows by one element.
You see it when every element leads to a yes or no choice, such as listing all subsets of n items.
10) Factorial Time - O(n!)
The work grows with the factorial of the input size.
It appears when you produce every possible ordering of n distinct items.
NOTES
- Big O describes how the running time grows as the input gets larger, not how many seconds a program takes.
- A constant time operation can still be slow if that constant is huge.