AlgoViz

Logarithms

easy 14 min

A logarithm answers "what power do I raise the base to?" In code, log2 n is how many times you can halve n before reaching 1, which is why binary search, balanced trees and divide and conquer all run in O(log n) and barely slow down as data grows.

See it run

Watch 64 shrink to 1 in six halvings, binary search find 42 in five looks, a 15-node tree stay four levels tall, and log n stay flat while n climbs.

Operations

Repeated Halving

The core idea: $\log_2 n$ is the number of times you can divide $n$ by 2 before you reach 1. Every logarithmic algorithm is this loop in disguise.

Step 1 of 10

Start with n = 64

  1. 64n
  2. 32
  3. 16
  4. 8
  5. 4
  6. 2
  7. 1
n = 64halvings = 0

How many times can we cut 64 in half before we reach 1? That count is \log_2 64. Put another way: 2 raised to what power gives 64?

Step 1: Start with n = 64

def count_halvings(n):    count = 0    while n > 1:        n //= 2          # integer halving        count += 1    return countprint(count_halvings(64))      # 6, because 2**6 == 64print(count_halvings(1000))    # 9, the floor of log2(1000) = 9.97print((64).bit_length() - 1)   # 6, read straight from the bitsprint((1000).bit_length() - 1) # 9
Time
O(log n)
Space
O(1)
subtract 1 each step
O(n) steps
exact answer from bits
n.bit_length() - 1

Whenever a loop divides its variable by a constant (n //= 2, n //= 10), the loop runs O(log n) times. Whenever it subtracts a constant, it runs O(n) times.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Trusting floating-point logs for integer answers

    major

    math.log(1000, 10) is 2.9999999999999996, so int() gives 2. Floats are fine for estimates; for exact integer logs use bit_length or an integer loop.

    Wrong
    import mathdigits = int(math.log(1000, 10)) + 1   # 3, should be 4
    Right
    digits = len(str(1000))                # 4floor_log2 = (1000).bit_length() - 1   # 9, exact
  • Halving with / instead of //

    major

    True division keeps going past whole numbers (1000 / 2 ten times is 0.977), so the count comes out one too high and the variable is no longer an int.

    Wrong
    count = 0while n > 1:    n = n / 2      # float division    count += 1
    Right
    count = 0while n > 1:    n //= 2        # integer halving    count += 1
  • Calling a loop logarithmic when it subtracts

    critical

    Taking away a constant each step, even a big one, still needs n / c steps, which is O(n). Only dividing by a constant gives O(log n).

    Wrong
    while n > 0:    n -= 2         # O(n): 1,000,000 takes 500,000 steps
    Right
    while n > 0:    n //= 2        # O(log n): 1,000,000 takes 20 steps
  • Binary searching unsorted data

    critical

    Throwing away half the array is only safe when order tells you which half the target cannot be in. On unsorted data the answer is simply wrong.

    Wrong
    arr = [7, 2, 9, 4, 1]binary_search(arr, 4)   # may miss 4
    Right
    arr = sorted([7, 2, 9, 4, 1])   # sort once, O(n log n)binary_search(arr, 4)           # then each search is O(log n)
  • Off-by-one in the loop condition

    major

    With right = len(arr) - 1 the range is inclusive, so the loop must run while left <= right. Using < skips the last remaining candidate.

    Wrong
    left, right = 0, len(arr) - 1while left < right:     # misses the final single element
    Right
    left, right = 0, len(arr) - 1while left <= right:    # checks every candidate
  • Treating log bases as different complexity classes

    minor

    log10 n, ln n and log2 n differ only by a constant factor, and Big-O drops constants. Write O(log n) and stop there.

    Wrong
    # "this is O(log10 n), so it is faster than O(log2 n)"
    Right
    # log10(n) = log2(n) / log2(10), a constant factor apart# both are simply O(log n)

Interview tips

  • Spot it fast

    • The problem size is divided by a constant each step.
    • Sorted input plus a search question: think binary search.
    • Walking root to leaf in a balanced tree or heap.
    • Constraints up to 10^9 or 10^18 often mean O(log n) is expected.
  • Numbers to know cold

    • 2^10 = 1,024, so log2 of a thousand is about 10.
    • log2 of a million is about 20; of a billion about 30.
    • Doubling n adds exactly one to log2 n.
    • A balanced tree of n nodes has height floor(log2 n).
  • Say it in the interview

    • "Each step halves the search space, so after k steps n / 2^k remain; that hits 1 when k = log2 n."
    • "The base does not matter in Big-O; it only changes a constant factor."
    • Mention that binary search needs sorted data and that the tree must stay balanced.
  • Traps

    • log(a + b) is not log a + log b.
    • Floating-point logs can be off by a hair; use integer methods for exact answers.
    • An unbalanced BST degrades to O(n).