Time Complexity Calculation Rules & Common Runtime Patterns
Time Complexity Calculation Rules & Common Runtime Patterns
To master technical interviews and algorithm design, you must be able to calculate the exact Big-O time complexity of arbitrary code by sight. This tutorial establishes the 4 fundamental arithmetic rules of Big-O and breaks down common loops, recursion, and nested patterns.
1. Real-World Analogy: Traveling Across Town
Suppose you travel from your house to an international airport:
- 1You walk 3 minutes to your driveway.
- 2You drive 45 minutes on the highway.
- 3You wait 4 hours for an international flight.
When someone asks how long your journey took, you say: "Around 4 to 5 hours." You do not say "4 hours, 45 minutes, and 180 seconds." In Big-O analysis, we drop non-dominant constants and lower-order terms because as journeys scale to days, walking down the driveway contributes virtually zero percentage to the total duration.
2. The 4 Golden Rules of Big-O Calculation
Rule 1: Drop Constants
$O(2n)$, $O(50n)$, and $O(\frac{n}{2})$ all simplify to $O(n)$.
Rule 2: Different Steps Add Together
If your code does one task followed by a completely different task with different inputs, add their complexities:
Rule 3: Nested Steps Multiply
When an inner loop executes once for every single iteration of an outer loop, multiply their complexities:
Rule 4: Drop Non-Dominant Terms
Keep only the term with the steepest asymptotic growth rate:
- $O(n^2 + n) \implies O(n^2)$
- $O(n + \log n) \implies O(n)$
- $O(2^n + n^{100}) \implies O(2^n)$
3. Loop Analysis Patterns
Pattern A: Halving Loop Variables $\implies O(\log n)$
Whenever a loop counter multiplies or divides by a factor on each iteration, the complexity is logarithmic:
Pattern B: Dependent Inner Loops
4. Multi-Language Implementations: Sieve of Eratosthenes ($O(n \log \log n)$)
The classical Sieve algorithm calculates all prime numbers up to $n$:
Python 3:
Modern JavaScript / TypeScript:
5. Dry-Run Step Table: Halving Loop (n = 64)
| Iteration | Counter value (i) | Condition (i < 64) | Steps Completed |
|---|---|---|---|
| 1 | 1 | True | 1 |
| 2 | 2 | True | 2 |
| 3 | 4 | True | 3 |
| 4 | 8 | True | 4 |
| 5 | 16 | True | 5 |
| 6 | 32 | True | 6 |
| 7 | 64 | False (Loop Terminates) | $\mathbf{\log_2(64) = 6\text{ steps!}}$ |
Multiple Choice Questions
str[1:]) or array cloning (arr.slice())?Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.