Skip to content

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

    Java / Big-O and Complexity

    Best, Worst and Average Case; Ω and Θ

    Worst case — the maximum steps over all inputs of size n. This is what interviewers mean by default. It's a guarantee.

    Chapter 5 of 113 min read

    The Plain Picture#

    Searching for your keys in a row of 10 drawers. Best case: first drawer. Worst case: last drawer (or not there at all). Average: somewhere in the middle. "How long does it take?" depends on which case you mean.

    The Real Names#

    • Worst case — the maximum steps over all inputs of size n. This is what interviewers mean by default. It's a guarantee.

    • Best case — the minimum. Rarely useful ("linear search is O(1) if the item is first" tells you nothing).

    • Average case — the expected steps over typical/random inputs. Important for hash tables and quicksort.

    • Three notations:

      • O (Big-O) — upper bound: grows no faster than.

      • Ω (Big-Omega) — lower bound: grows at least as fast as.

      • Θ (Big-Theta) — tight bound: both — grows exactly like (up to constants).

      Engineers usually say "O" when they mean a tight bound ("this loop is O(n)"). That's fine in interviews; just know the difference exists.

    Under the Hood — examples that matter#

    OperationBestAverageWorstWhy the worst case happens
    linear searchO(1)O(n)O(n)item at the end or missing
    HashMap.getO(1)O(1)O(log n) in Java 8+ (O(n) in older Java)many keys in the same bucket (Collections, From the Inside)
    quicksortO(n log n)O(n log n)O(n²)always picking a bad pivot (Sorting (coming soon))
    insertion sortO(n) (already sorted)O(n²)O(n²)reverse-sorted input

    When you state a complexity in an interview, say which case: "O(n) on average, because hash-set insertion is expected constant time."

    Check yourself

    3 questions
    1

    Which case do interviewers mean by default?

    Show answer

    The worst case.

    2

    What's the difference between O, Ω and Θ?

    Show answer

    Upper bound, lower bound, tight (both) bound.

    3

    Why do we usually quote HashMap operations as O(1) even though the worst case is worse?

    Show answer

    With a good hash function the expected (average) cost is constant, and the worst case is rare in practice.