Skip to content
Visual explainer 3h to learn 4 steps

Analysing loops & recursive code

Derive the running time of loops, nested loops and simple recursions by inspection.

By Invicly Tech, , in Data Structures & Algorithms. About 9 minutes to read.

Topic 2 of 54

In short

You can usually read an algorithm's complexity straight from its structure. Sequential blocks add, nested loops multiply, and a loop that halves its range runs log n times. Recursive functions are analysed by writing a recurrence and solving it, often with the master theorem.

Explained simply

You do not need to run code to know how it will scale. You can read it, like reading a recipe and guessing how long dinner will take. Each loop, each nested loop and each recursive call adds a predictable amount of work.

Steps that come one after another add up. Loops inside loops multiply. If you walk a list once and then walk it again, that is n + n, still O(n). If for every item you walk the whole list again, that is n times n, which is O(n^2).

A loop that cuts its range in half each time is special. Think of tearing a phone book in half again and again until one page is left. A book of 1,000 pages needs only about 10 tears. That kind of loop is O(log n).

Recursive functions are functions that call themselves. To analyse them, you write a small equation called a recurrence, such as "the work for n equals the work for n/2 plus a little extra". Then you solve it by drawing the calls as a tree and adding up each level.

Press Play on a diagram to walk through it one step at a time.

MapRecursion tree for T(n) = 2T(n/2) + n
n work at the top
  • Level 1: 2 calls of n/2
    • Total n
  • Level 2: 4 calls of n/4
    • Total n
  • Level log n: n calls of 1
    • Total n
  • log n levels x n each
    • O(n log n)
MapRecursion tree for binary search, T(n) = T(n/2) + 1
n = 16: 1 unit of work
  • n = 8: 1 unit
    • only one branch per level
  • n = 4: 1 unit
    • range halves each time
  • n = 2: 1 unit
  • n = 1: 1 unit
    • about log2(16) + 1 = 5 levels
    • total O(log n)
CompareLoop shapes and their cost
Linear shapes
  • One loop over n: O(n)
  • Two loops one after another: O(n)
  • Inner loop of fixed size 5: O(n)
Quadratic shapes
  • for i in n, for j in n: O(n^2)
  • for j in range(i): O(n^2)
  • x in list inside a loop: O(n^2)
Log shapes
  • i *= 2 until n: O(log n)
  • n loop with halving inside: O(n log n)
  • Halving recursion, one call: O(log n)

In depth

Count what the inner line does in total

The most reliable trick is to ask: how many times does the innermost line run, added up over the whole program?

For "for i in range(n): for j in range(i)", the inner line runs 0 + 1 + 2 + ... + (n-1) times. That sum is n(n-1)/2, so it is O(n^2) even though the inner loop is shorter at the start.

But if the inner loop is "for j in range(5)", it runs 5n times in total, which is O(n). A nested loop is only quadratic when both loops grow with n.

  • Sequential blocks: add
  • Nested loops: multiply only if both depend on n
  • Watch built-ins: xs.insert(0, v), slicing and x in list are O(n)

Spotting logarithms

Any loop where the variable is multiplied or divided by a constant each round runs O(log n) times. "i = 1; while i < n: i *= 2" runs about log2 n times. Binary search is the classic example.

A common trap: "for i in range(n): j = n; while j > 1: j //= 2" is O(n log n). The outer loop runs n times and the inner halving loop runs log n times each round. Multiply them.

Writing a recurrence from code

For a recursive function, write T(n), the cost for input size n. Look at the body. Each recursive call adds a T(smaller size). Everything else is the extra work f(n).

Merge sort calls itself on two halves and then merges in linear time: T(n) = 2T(n/2) + n. Binary search makes one call on half the range and does constant work: T(n) = T(n/2) + 1. Computing factorial makes one call on n - 1: T(n) = T(n-1) + 1, which is O(n).

The master theorem in plain words

For T(n) = a T(n/b) + n^d, compare a (how many calls) with b^d (how much the extra work shrinks per level).

If a < b^d, the top level dominates: O(n^d). If a = b^d, every level costs about the same, and there are log n levels: O(n^d log n). If a > b^d, the leaves dominate because calls multiply faster than work shrinks: O(n^(log_b a)).

  • Merge sort: a=2, b=2, d=1, equal, so O(n log n)
  • Binary search: a=1, b=2, d=0, equal, so O(log n)
  • Karatsuba: a=3, b=2, d=1, leaves win, so O(n^1.58)
MapMaster theorem: three outcomes
T(n) = a T(n/b) + n^d
  • a < b^d
    • Top level dominates
    • O(n^d)
  • a = b^d
    • Every level costs the same
    • O(n^d log n)
    • Merge sort, binary search
  • a > b^d
    • Leaves dominate
    • O(n^(log_b a))
    • Karatsuba: O(n^1.58)

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Count work in sequential and nested loops~45m
  2. 2
    Spot logarithmic halving loops~45m
  3. 3
    Write recurrences for recursive functions~45m
  4. 4
    Apply the master theorem to common recurrences~45m

Key points

  • Sequential steps add: O(n) + O(n^2) is O(n^2).
  • Nested loops multiply: an inner O(m) loop inside an O(n) loop is O(n*m).
  • Halving or doubling a loop variable gives O(log n) iterations.
  • Master theorem: T(n) = aT(n/b) + O(n^d) compares a with b^d to pick the dominant term.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def count_halvings(n):   # O(log n)
    steps = 0
    while n > 1:
        n //= 2
        steps += 1
    return steps

def triangle(n):         # O(n^2): 0 + 1 + ... + (n-1) inner steps
    total = 0
    for i in range(n):
        for j in range(i):
            total += 1
    return total

Tracing a halving loop on n = 20

Start with n = 20. Each round does n //= 2: 20 -> 10 -> 5 -> 2 -> 1. That is 4 rounds. log2(20) is about 4.3, and rounding down gives 4. If n were one million, the loop would run only 19 times. That is why logarithmic loops feel almost free.

python
def halvings(n):
    rounds = 0
    while n > 1:
        n //= 2
        rounds += 1
    return rounds

print(halvings(20))         # 4
print(halvings(1_000_000))  # 19

Analysing a hidden quadratic

The code below looks like one loop, so it seems O(n). But "x not in result" scans the list result, which can hold up to n items. So each round may cost O(n), and n rounds cost O(n^2). On 10,000 distinct items, that is up to 50 million comparisons. Swapping the list for a set makes the check O(1) on average, and the whole function O(n).

python
def unique_slow(xs):          # O(n^2)
    result = []
    for x in xs:
        if x not in result:   # scans result: O(n)
            result.append(x)
    return result

def unique_fast(xs):          # O(n)
    seen, result = set(), []
    for x in xs:
        if x not in seen:     # O(1) average
            seen.add(x)
            result.append(x)
    return result

Quick reference

  • One loop over n: O(n). Two nested loops over n: O(n^2)
  • 0 + 1 + ... + (n-1) = n(n-1)/2, which is O(n^2)
  • Multiply or divide the loop variable each round: O(log n)
  • T(n) = T(n/2) + O(1) gives O(log n)
  • T(n) = 2T(n/2) + O(n) gives O(n log n)
  • T(n) = T(n-1) + O(1) gives O(n); T(n) = 2T(n-1) + O(1) gives O(2^n)
  • Count built-in costs: x in list, slicing and insert(0, x) are O(n)

Common mistakes

  • Assuming a nested loop is always O(n^2) when the inner loop is bounded by a constant.
  • Forgetting the cost of built-in calls inside loops, such as list.insert(0, x) or slicing.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the cost of: for i in range(n): for j in range(10): work()?

Question 2

2What does T(n) = 2T(n/2) + n solve to?

Question 3

3A loop starts at i = n and does i = i // 3 until i is 0. How many rounds?

Question 4

4What does T(n) = 2T(n-1) + 1 solve to?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write count_digits(n) that counts the decimal digits of a positive integer using a loop that divides by 10. Example: 4096 returns 4. What is its complexity in terms of n?

  2. Exercise 2medium

    Write power(x, n) that computes x to the power n using recursion with halving: x^n = (x^(n/2))^2, times x if n is odd. Example: power(3, 5) returns 243. Write its recurrence.

  3. Exercise 3hard

    Write count_calls(n) that returns how many times a naive recursive fib(n) gets called, where fib(n) = fib(n-1) + fib(n-2) and fib(0), fib(1) are base cases. Example: count_calls(5) returns 15. Explain why the growth is exponential.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need the master theorem for interviews?
Rarely by name. But knowing the three common results, O(log n), O(n log n) and O(2^n), for the usual recursions is expected.
How do I analyse code with a while loop that moves two pointers?
Count the total moves. If each round moves at least one pointer forward and pointers never move back, the total is at most n rounds, so O(n).
Why is my one-loop function slow?
Look for hidden loops inside it: x in list, list.index, string concatenation, slicing or sorting inside the loop each cost O(n) or more per round.

Go deeper

ShareXLinkedInWhatsApp