Sub topic 3
Mixing Linear and Logarithmic Loops
This chapter assumes you can count single loops, add costs of sequential blocks, multiply costs of nested loops, and count halving loops as about log2 n iterations.
Linear Outer, Logarithmic Inner
When a halving loop sits inside a loop that runs n times, the costs multiply. The inner loop's bound does not depend on i, so each pass costs the same.
def count_nlogn(n):
steps = 0
for i in range(n):
j = n
while j > 0:
j //= 2
steps += 1
return steps
print(count_nlogn(8)) # 32, which is 8 * 8.bit_length()The exact count is n · (floor(log2 n) + 1).
Dropping Constants: Big-O and Big-Theta
Exact counts depend on small details, but growth depends only on the dominant term. For a count such as 3n² + 5n + 2, you drop the lower-order terms and the constant factor, which leaves Θ(n²). Big-O gives an upper bound. Big-Theta gives a tight bound, meaning the count is both an upper and a lower bound up to a constant factor. The count above is Θ(n log n).
| Exact count | Order of growth |
|---|---|
| n(n − 1)/2 | Θ(n²) |
| floor(log2 n) + 1 | Θ(log n) |
| n · (floor(log2 n) + 1) | Θ(n log n) |
Early Exits: Best and Worst Cases
A loop that can return early has no single count. Linear search takes 1 step when the target comes first and n steps when the target is missing. You state each case separately: the best case is Θ(1) and the worst case is Θ(n).
Hidden Loops in Built-in Operations
x in some_list scans the list, so it costs up to len(list) steps. Slicing, list.index, and sum also loop internally. A single loop whose body contains x in b is O(len(a) · len(b)). Converting b to a set gives average O(1) lookups.
Checking Your Count with a Counter
Make the code return its step count, then assert that it matches your formula over several inputs:
for n in (1, 7, 8, 1000):
assert count_nlogn(n) == n * n.bit_length()
print("formula holds")If an assertion fails, the error is usually off by one in the loop bounds.
Exercise
How many times does steps += 1 run in this code, as an exact count and as an order of growth? for i in range(n): k = 1; while k < n: k *= 2; steps += 1 (the while loop is nested inside the for loop).
Show answer
For n >= 2 the inner loop runs ceil(log2 n) times, so the total is n * ceil(log2 n). For n = 1 it is 0. The order of growth is Theta(n log n). Check: when n = 8, k takes the values 1, 2, 4, which gives 3 inner iterations and 24 in total.