AlgoViz

O(log n) logarithmic time

easy 14 min

O(log n) means each step cuts the remaining work by a constant factor, usually half.

See it run

Watch binary search, a balanced BST and fast power each throw away half the work per step, then see how flat log n stays as n grows to a million.

Operations

Binary search

Find 11 in the sorted array [1, 3, 5, 7, 9, 11, 13, 15]. Each check of the middle discards half of what is left.

Step 1 of 6

Set up the search range

  1. 10L
  2. 31
  3. 52
  4. 73
  5. 94
  6. 115
  7. 136
  8. 157R
left = 0right = 7space = 8steps = 0

The array is sorted, so the middle tells us which half can hold 11. L starts at index 0 and R at index 7: the search space is all 8 cells. Halving 8 down to 1 takes \log_2 8 = 3 halvings, so we need at most 4 checks.

Step 1: Set up the search range

def binary_search(arr, target):    left, right = 0, len(arr) - 1    steps = 0    while left <= right:        mid = (left + right) // 2        steps += 1        if arr[mid] == target:            return mid        elif arr[mid] < target:            left = mid + 1      # target is in the right half        else:            right = mid - 1     # target is in the left half    return -1
Time
O(log n)
Space
O(1)
vs linear search
O(n): up to 8 checks here
1,024 items
at most 11 checks

Binary search needs two things: sorted data and O(1) jumps to the middle. With both, 1,024 items take at most 11 checks and a billion take about 30.

Common mistakes

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

  • Binary searching unsorted data

    critical

    Binary search decides which half to throw away by comparing with the middle. On unsorted data that decision is meaningless, so it silently returns -1 for values that are present.

    Wrong
    nums = [9, 2, 7, 4, 1]idx = binary_search(nums, 4)   # may miss 4
    Right
    nums = sorted([9, 2, 7, 4, 1])  # O(n log n) onceidx = binary_search(nums, 4)     # then O(log n) per search
  • Moving a bound to mid instead of past it

    critical

    With left <= right, setting left = mid can leave the range unchanged (for example left = right = mid), so the loop never ends. The middle was already checked; step past it.

    Wrong
    while left <= right:    mid = (left + right) // 2    if arr[mid] < target:        left = mid          # can loop forever
    Right
    while left <= right:    mid = (left + right) // 2    if arr[mid] < target:        left = mid + 1      # mid is ruled out
  • Using left < right with right = mid - 1

    major

    Mixing loop styles skips the last remaining cell. With a closed range [left, right] the loop must run while left <= right, or a one-element array is never checked.

    Wrong
    left, right = 0, len(arr) - 1while left < right:          # [5] with target 5 returns -1    ...
    Right
    left, right = 0, len(arr) - 1while left <= right:         # closed range: check until empty    ...
  • Calling a plain BST lookup O(log n)

    major

    A BST is only O(log n) when it is balanced. Inserting sorted keys into a plain BST builds a chain of height n, so every lookup becomes O(n).

    Wrong
    root = Nonefor key in range(1, 100001):     # sorted inserts    root = insert(root, key)     # height 100,000
    Right
    import bisectkeys = list(range(1, 100001))    # sorted list + bisecti = bisect.bisect_left(keys, 4242)  # O(log n) guaranteed
  • Computing a power with a plain loop

    major

    Multiplying base by itself exp times is O(exp). For exp = 10^18 that never finishes. Square and halve instead, or use Python's three-argument pow for modular powers.

    Wrong
    result = 1for _ in range(exp):        # O(exp)    result = result * base % mod
    Right
    result = pow(base, exp, mod)   # O(log exp) built-in# or fast_power with % mod after each multiply
  • Overflow-prone midpoint in fixed-width languages

    minor

    In Java or C++, (left + right) / 2 can overflow when both are near the int limit. Python integers never overflow, but the safe form is a good habit and interviewers notice it.

    Wrong
    mid = (left + right) // 2       # overflows in Java/C++
    Right
    mid = left + (right - left) // 2  # safe everywhere

Interview tips

  • How to explain it

    • O(log n) means each step cuts the remaining work by a constant factor, usually half.
    • Halving n until it reaches 1 takes log₂ n steps, so 1,024 items need about 10 steps.
    • Doubling the input adds only one step. A billion sorted items take about 30 comparisons.
    • The base of the log does not matter in Big O: log₂ n and log₁₀ n differ by a constant factor.
  • Spot it in code

    • A loop that does `n //= 2` or `i *= 2` runs O(log n) times.
    • `left = mid + 1` or `right = mid - 1` inside a loop: binary search.
    • `base *= base; exp //= 2`: exponentiation by squaring.
    • Walking one root-to-leaf path in a balanced tree or heap: O(log n).
  • Memory tricks

    • LOG = LOOKUP Or GUESS: split it in half like a phone book.
    • Guessing a number from 1 to 100 takes at most 7 guesses.
    • Fold a sheet of paper 7 times and you get 128 layers; going back, 128 needs 7 halvings to reach 1.
    • 2^10 ≈ 1,000, so every three zeros in n adds about 10 steps.
  • Watch out

    • Binary search needs sorted data and random access; a linked list cannot jump to the middle in O(1).
    • Sorting first costs O(n log n), worth it only when you search many times.
    • BST operations are O(log n) only when the tree is balanced.