Guide - How To Measure Time Complexity
Guide - How To Measure Time Complexity
🚀
This guide should help you quickly analyze time complexity by
recognizing common patterns in code!
1. Loop-Based Patterns
Pattern Code Example Time
Complexity
Single Loop for (int i = 0; i < n; i++) O(n)
Nested Loops for (int i = 0; i < n; i++) O(n²)
for (int j = 0; j < n; j++)
Triple Nested Loops for (int i = 0; i < n; i++) O(n³)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
*Loop with Increment (i = for (int i = 1; i < n; i *= 2) O(log n)
2, i += constant)
Loop with Decrement (i /= for (int i = n; i > 0; i /= 2) O(log n)
2)
2. Recursive Patterns
Pattern Recurrence Relation Time Complexity
Linear Recursion T(n) = T(n-1) + O(1) O(n)
Binary Recursion T(n) = 2T(n/2) + O(1) O(n)
Divide & Conquer (Merge T(n) = 2T(n/2) + O(n) O(n log n)
Sort, Quick Sort Worst
Case)
Exponential Recursion T(n) = T(n-1) + T(n-2) O(2ⁿ)
(Fibonacci, Brute Force
DFS)
3. Divide and Conquer Patterns
Algorithm Recurrence Complexity
Binary Search T(n) = T(n/2) + O(1) O(log n)
Merge Sort T(n) = 2T(n/2) + O(n) O(n log n)
Quick Sort (Best & Avg) T(n) = T(n/2) + O(n) O(n log n)
Quick Sort (Worst Case - T(n) = T(n-1) + O(n) O(n²)
sorted array)
5. Graph Algorithms
Algorithm Complexity
BFS / DFS (Adjacency List) O(V + E)
Dijkstra (Min Heap) O((V + E) log V)
Bellman-Ford O(VE)
Floyd Warshall (All-Pairs O(V³)
Shortest Path)
Prim’s / Kruskal’s MST O(E log V)
6. Sorting Algorithms
Algorithm Best Worst Case
Case
Bubble Sort / O(n) O(n²)
Insertion Sort
Merge Sort O(n log O(n log n)
n)
Quick Sort O(n log O(n²)
n)
Heap Sort O(n log O(n log n)
n)
8. Special Cases
Case Exam
ple
Iterating All Subsets O(2ⁿ)
Iterating All O(n!)
Permutations
Brute Force Checking O(n²)
All Pairs