Time Complexity: The Complete Hierarchy
Every algorithm falls into a specific "class" of speed. This guide covers all 8 major types of Time Complexities, ordered from the absolute fastest to the impossible slow.
O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(n³) < O(2ⁿ) < O(n!)
1. O(1) – Constant Time FASTEST
Concept: The runtime never changes, regardless of input size.
Example: Accessing an array index or checking a dictionary key.
2. O(log n) – Logarithmic Time VERY FAST
Concept: The problem size is cut in half at each step. Common in binary search and balanced trees.
Example: Finding a number in a sorted phonebook.
3. O(n) – Linear Time FAST
Concept: Runtime grows directly with input. If you have 10 items, it does 10 operations.
Example: Looping through a list to find the max value.
4. O(n log n) – Linearithmic Time DECENT
Concept: Slightly slower than linear, but much faster than quadratic. This is the standard for efficient sorting algorithms (Merge Sort, Heap Sort, Quick Sort).
Analogy: Sorting a deck of cards efficiently.
5. O(n²) – Quadratic Time SLOW
Concept: Growth is the square of the input. Common in algorithms with nested loops (Loop inside a loop).
Example: Bubble Sort, Insertion Sort.
6. O(n³) – Cubic Time VERY SLOW
Concept: Loop inside a loop inside a loop. Rarely used in practice except for specific mathematical operations (like simple matrix multiplication).
7. O(2ⁿ) – Exponential Time TERRIBLE
Concept: The operations double with every single new input. This is common in "Brute Force" recursion.
Example: Finding all subsets of a set, Recursive Fibonacci.
8. O(n!) – Factorial Time IMPOSSIBLE
Concept: The absolute slowest. It grows astronomically fast. Even small inputs like n=20 can take years to process.
Example: The Traveling Salesman Problem (checking every possible route between cities).
Summary: Which one should I use?
- ✅ O(1) & O(log n): Excellent. Aim for this.
- ✅ O(n): Good standard for processing data.
- ⚠️ O(n log n): Acceptable for sorting.
- ❌ O(n²): Avoid if n > 5,000.
- ⛔ O(2ⁿ) & O(n!): Only for very small inputs (n < 20).