Now that you know what Big O is, let's learn how to count operations to figure out the time complexity of code. 🔍
💡 Think of it like this: Imagine you're counting how many steps it takes to walk somewhere. More steps = takes longer. In code, we count how many "steps" (operations) the computer needs to do.
# Example 1: O(1) — constant time (always 1 step)
def get_first(arr):
return arr[0] # Just one operation, no matter how big arr is!
# Example 2: O(n) — linear time (steps grow with input size)
def print_all(arr):
for item in arr: # If arr has 100 items, this runs 100 times
print(item) # n items → n steps
# Example 3: O(n²) — quadratic time (steps grow MUCH faster)
def print_pairs(arr):
for i in arr: # n times
for j in arr: # n times for EACH i
print(i, j) # n × n = n² total steps!
Quick comparison for n = 1,000:
📋 Instructions
Analyze the three functions below. For each, print its Big O complexity.
The functions are already written — you just need to figure out their complexity and print the answers.
```python
def func_a(n):
for i in range(n):
print(i)
def func_b(n):
for i in range(n):
for j in range(n):
print(i, j)
def func_c(n):
return n * 2
```
Print the complexity for each:
```
func_a: O(n)
func_b: O(?)
func_c: O(?)
```
func_b has a nested loop (loop inside a loop). If each loop runs n times, the total is n × n. func_c does just one multiplication regardless of n — that's constant time.