Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Big-O and Complexity

    Logarithms From Zero

    log₂ n ("log base 2 of n") — the power you raise 2 to, to get n. Since 2¹⁰ = 1,024, log₂ 1,024 = 10.

    Chapter 3 of 113 min read

    The Plain Picture#

    Guess a number between 1 and 1,000. After each guess I say "higher" or "lower". The smart strategy: always guess the middle. Each answer throws away half of the remaining numbers:

    Output
      1,000 → 500 → 250 → 125 → 63 → 32 → 16 → 8 → 4 → 2 → 1        about 10 guesses

    Even for 1,000,000 numbers you need only about 20 guesses. "How many times can I halve n until 1 is left?" — that number is the logarithm.

    The Real Names#

    • log₂ n ("log base 2 of n") = the power you raise 2 to, to get n. Since 2¹⁰ = 1,024, log₂ 1,024 = 10. Equivalently: how many times you can halve n before reaching 1, or how many doublings from 1 reach n.

    • In complexity, "log n" means log₂ n unless stated otherwise. The base doesn't matter in Big-O: log₁₀ n and log₂ n differ only by a constant factor (log₂ n ≈ 3.32 × log₁₀ n), and constants are dropped.

    nlog₂ n (rounded)
    1,00010
    1,000,00020
    1,000,000,00030
    2³² ≈ 4.3 billion32

    Logarithms grow incredibly slowly. Going from a thousand to a billion items — a million times more — only triples the steps.

    Under the Hood — measured#

    Binary search on a sorted array (fully taught in Binary Search (coming soon)), counting loop rounds for a value that isn't there:

    Output
    binary search in 1000 items (not found): 9 steps
    binary search in 1000000 items (not found): 19 steps
    binary search in 100000000 items (not found): 26 steps

    Close to log₂ n every time (≈10, 20, 27). And a loop that doubles its counter:

    Java
    for (int i = 1; i < 1_000_000; i *= 2) count++;
    // doubling loop to 1,000,000: 20 rounds

    Where you'll see log n: binary search; balanced trees like TreeMap (Collections, From the Inside) — height log n; heaps (PriorityQueue) — insert and remove in log n; the "log n" levels of divide-and-conquer sorting (Ch 8); and any loop where the problem size is multiplied or divided by a constant each round.

    Check yourself

    3 questions
    1

    What's log₂ 64? log₂ 1,048,576?

    Show answer

    6; 20.

    2

    Why doesn't the base of the logarithm matter in Big-O?

    Show answer

    Logs of different bases differ only by a constant factor, which Big-O drops.

    3

    What's the complexity of for (int i = n; i > 1; i /= 3)?

    Show answer

    O(log n) — n is divided by a constant each round.