Skip to content

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

    Java / Big-O and Complexity

    From Constraints to Algorithm

    Before a trip, you check how far it is. 2 km — walk. 20 km — take a scooter. 2,000 km — you need a plane. The distance tells you which vehicle

    Chapter 10 of 114 min readOften asked in interviews

    The Plain Picture#

    Before a trip, you check how far it is. 2 km — walk. 20 km — take a scooter. 2,000 km — you need a plane. The distance tells you which vehicle is even possible, before you plan the route.

    The Real Name#

    Every competitive-programming problem and most interview problems state constraints like 1 ≤ n ≤ 10⁵. Combined with a rough speed of about 10⁸ simple operations per second, the constraint tells you which complexities can pass — often it tells you the intended algorithm.

    Measured on this Mac:

    Output
    100 million simple ops: 62 ms

    That's faster than 10⁸/s, because the loop is trivial and the JIT is excellent. Real solutions do more per step (memory access, objects, bounds checks), so 10⁸ per second is a safe planning number, and typical time limits are 1–2 seconds.

    Under the Hood — the table to memorise#

    Largest nAllowed complexityTypical techniques
    n ≤ 10–11O(n!)all permutations, brute force
    n ≤ 20–25O(2ⁿ), O(2ⁿ · n)all subsets, bitmask DP (Bit Manipulation (coming soon))
    n ≤ 100–500O(n³)triple loops, some DP, Floyd–Warshall
    n ≤ 2,000–5,000O(n²)pairs, 2-D DP
    n ≤ 10⁵–10⁶O(n log n) or O(n)sorting, heaps, binary search, hash maps, two pointers, sliding window
    n ≤ 10⁸O(n) with tiny constantsa single simple pass
    n ≥ 10⁹ / 10¹⁸O(log n) or O(1)binary search on the answer, maths formulas, fast exponentiation

    How to use it in an interview:

    1. Read the constraint. "n up to 10⁵" → quadratic is 10¹⁰ steps → too slow → the answer must be about O(n log n) or better. This rules out brute force before you write it.

    2. Say the brute force and its complexity out loud anyway ("the naïve way checks every pair, O(n²), which is 10¹⁰ for 10⁵ — too slow"), then improve it. Interviewers want to see this reasoning.

    3. After coding, state time and space complexity without being asked, and name the dominant step.

    If an interviewer gives no constraints, ask: "roughly how large can the input be?"

    Check yourself

    4 questions
    1

    n ≤ 10⁵. Is an O(n²) solution acceptable? Why?

    Show answer

    No — about 10¹⁰ operations, roughly 100 seconds at 10⁸/s; aim for O(n log n) or O(n).

    2

    n ≤ 18. What complexity class is probably intended?

    Show answer

    Exponential, like O(2ⁿ) — subsets or bitmasks.

    3

    n ≤ 10¹⁸. What must the algorithm be?

    Show answer

    O(log n) or O(1) — you can't even loop to n.

    4

    The interviewer gives no size. What do you do?

    Show answer

    Ask for the expected input size (and still state the complexity of your solution).