Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 1

Reading Loops: From Code to a Bound

Walk through four loop patterns—independent multi-input loops, triangular loops, halving loops and early exits—to derive tight time and space bounds directly from code.

Contentsand lesson path

What you will learn

  • Derive Big-O time and space bounds for code with sequential, nested and multi-input loops, dropping constants and lower-order terms correctly.

Prerequisites: Python Foundations

01. The problem

In Counting Steps Instead of Seconds, you saw why step counts beat wall-clock seconds. In day-to-day work or code review, however, you rarely have an instrumented steps counter handy—you look at a 15-line function and need its time and space bounds in under a minute.

The trap is relying on surface patterns such as "two nested for loops always mean O(n^2)" or "a shrinking loop means O(log n)". Both shortcuts fail on real code: two nested loops over one input might shrink geometrically to O(n log n), or iterate over two different inputs n and m, or allocate an output far larger than the loop index variables. Below we trace four Python functions step by step under one constraint: every inner statement executes in O(1) time (no hidden linear scans inside in, list.count, or slices), and you must derive both time and space bounds before reading the summary.

02. Step 1: sequential phases with independent inputs

Start with audit_overlap(users, flags). The function runs one pass over users (length n) to compute a checksum, and then runs a separate double loop over flags (length m) to count equal pairs. Why do we sum rather than multiply? Because the second phase does not run inside each iteration of the first phase; the first loop finishes all n iterations before the double loop starts its m^2 comparisons.

Python · sequential phases on two inputs
def audit_overlap(users: list[int], flags: list[int]) -> tuple[int, int]:
    """Sum users, then count matching flag pairs; return (score, steps)."""
    steps = 0
    user_total = 0
    for u in users:
        steps += 1
        user_total += u

    flag_pairs = 0
    for i in range(len(flags)):
        for j in range(len(flags)):
            steps += 1
            if flags[i] == flags[j]:
                flag_pairs += 1
    return user_total + flag_pairs, steps


print("n=100, m=10:", audit_overlap(list(range(100)), list(range(10))))
print("n=10, m=100:", audit_overlap(list(range(10)), list(range(100))))
Expected output
n=100, m=10: (4960, 200)
n=10, m=100: (145, 10010)

Look at the two runs: when n = 100 and m = 10, each phase contributes 100 steps (200 total); when n = 10 and m = 100, the second phase dominates at 10,000 steps (10,010 total). Dropping neither variable gives O(n + m^2) time and O(1) auxiliary space (only scalar counters). Why can you not simplify O(n + m^2) to O(m^2)? Because n and m vary independently: if users has ten million records (n = 10^7) and flags has five settings (m = 5), the linear users scan dominates (10^7 vs 25).

What if flags were checked inside the users loop instead of after it? Then every one of the n users would trigger m^2 iterations, turning addition into multiplication: O(n * m^2). That single indentation shift is the difference between a fast sequential pipeline and a nested bottleneck.

03. Step 2: triangular loops and output space

In triangular_count(n), the outer index i runs from 0 to n - 1, and the inner index j starts at i instead of 0. Because the inner loop shrinks by one step each pass, it can be tempting to hope for O(n log n). Write out the exact sum instead: pass i = 0 runs n times, pass i = 1 runs n - 1 times, and the final pass i = n - 1 runs 1 time. Summing n + (n - 1) + ... + 1 gives n(n + 1) / 2 = (1/2)n^2 + (1/2)n. Dropping the 1/2 constant and the linear term leaves O(n^2)—shrinking by a fixed subtraction (- 1) never changes the quadratic class.

Python · triangular and halving loop counters
def triangular_count(n: int) -> int:
    steps = 0
    for i in range(n):
        for j in range(i, n):
            steps += 1
    return steps


def halving_steps(n: int) -> int:
    steps = 0
    cur = n
    while cur > 1:
        cur //= 2
        steps += 1
    return steps


for n in (5, 10, 20):
    print(f"triangular(n={n}): {triangular_count(n)} == {n * (n + 1) // 2}")
for n in (8, 64, 1024, 1_048_576):
    print(f"halving(n={n}): {halving_steps(n)} steps")
Expected output
triangular(n=5): 15 == 15
triangular(n=10): 55 == 55
triangular(n=20): 210 == 210
halving(n=8): 3 steps
halving(n=64): 6 steps
halving(n=1024): 10 steps
halving(n=1048576): 20 steps

Now check space on a triangular loop. Counting steps uses O(1) total and auxiliary space because no container grows with n. What if you changed triangular_count to append every (i, j) pair into an output list pairs and return it? The loop still runs O(n^2) steps, so pairs grows to n(n + 1) / 2 tuples: total space jumps from O(1) to O(n^2) even though the loop only keeps two integer variables i and j!

04. Step 3: geometric halving and early exits

Compare triangular_count with halving_steps in the snippet above. Instead of subtracting 1 on each iteration, cur //= 2 divides the remaining work by a constant factor of 2. Starting from 1,048,576, it takes only 20 steps to reach 1 because 2^20 = 1,048,576. Whenever a loop multiplies or divides its state variable by a constant k > 1 on every iteration, the iteration count is Theta(log n).

What if you place a halving loop inside an outer for i in range(n) loop? Each of the n outer passes runs O(log n) inner steps, multiplying to O(n log n). Conversely, what if a linear loop contains if x < 0: return True, steps as in has_negative below? An early exit improves the best case to O(1) (when index 0 is negative), yet the worst case remains O(n) because an input of all positive values forces the loop to inspect every element.

Python · early exit vs full scan
def has_negative(values: list[int]) -> tuple[bool, int]:
    steps = 0
    for x in values:
        steps += 1
        if x < 0:
            return True, steps
    return False, steps


print("early exit:", has_negative([-3, 1, 2, 3]))
print("full scan:", has_negative([1, 2, 3, 4]))
Expected output
early exit: (True, 1)
full scan: (False, 4)

05. Check your understanding

Practice check · 3 questions

Derive bounds from loop structure

Analyse these variations using the rules from Steps 1–3.

Q1. Consider `k = n` with `while k > 0:` that runs `for i in range(n): total += 1` inside, then sets `k //= 2`. What is the tight time bound?
Q2. Now suppose the inner loop runs `for i in range(k): total += 1` instead of `range(n)`, while `k` starts at `n` and halves (`k //= 2`) each pass. How many total steps execute?
Q3. A function loops `for x in nums:` (`len(nums) == n`) and appends `x` to `unique` only `if x not in unique:` (`unique` is a `list`). What is the worst-case time?
Practice only: not graded, not saved, not evidence.

06. Apply it

To connect this to the skill practice, write six small Python functions of your own—one each for O(1), O(log n), O(n), O(n log n), O(n^2), and O(n + m^2)—and derive both their time and space bounds on paper before adding a steps counter to check your prediction at n = 16 and n = 256.

Next, modify has_negative to return the indices of all negative items instead of stopping at the first one, and verify how both its best-case time and its total space change. When you are comfortable tracing loop counts, continue to Worst Case, Average Case and Amortized Cost.

07. Review prompt

Without looking back at the code:

  1. Why does for i in range(n): for j in range(i, n): remain O(n^2) while while k > 1: k //= 2 is O(log n)?
  2. What must you check inside a single-loop body before concluding the function is O(n)?
  3. Explain the difference between O(n + m^2) and O(n * m^2) in terms of loop placement.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check