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:
1
You walk 3 minutes to your driveway.
2
You drive 45 minutes on the highway.
3
You 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)$.
1# Even though there are two separate loops (2n operations), it is O(n)
2for x in items:# n operations
3print(x)
4for y in items:# n operations
5print(y)
6# Total: 2n -> 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:
1defprocess_data(list_a, list_b):
2for a in list_a:# Takes O(a)
3print(a)
4for b in list_b:# Takes O(b)
5print(b)
6# Total Time: O(a + b) [NOT O(n)!]
Rule 3: Nested Steps Multiply
When an inner loop executes once for every single iteration of an outer loop, multiply their complexities:
1for a in list_a:# Runs 'a' times
2for b in list_b:# Runs 'b' times for each 'a'
3print(a, b)
4# Total Time: O(a * b)
Rule 4: Drop Non-Dominant Terms
Keep only the term with the steepest asymptotic growth rate:
What is the simplified Big-O time complexity of an algorithm whose step count formula is $T(n) = 5n^3 + 200n^2 + 10,000$?
Question 2
What is the time complexity of the following code snippet?
PythonCode Snippet
1i = n
2while i >1:
3 i = i //2
Question 3
If a function iterates over an array of size $A$ in an outer loop, and inside it iterates over an entirely separate array of size $B$, what is the time complexity?
Question 4
What is the sum of the series $1 + 2 + 3 + \dots + n$, and what is its Big-O complexity?
Question 5
What common mistake do engineers make when calculating the complexity of built-in functions like string slicing (str[1:]) or array cloning (arr.slice())?
Next Lesson
Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.