Skip to content

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

    Java / Big-O and Complexity

    Costs of Everyday Java Operations

    Memorise this table. Hidden costs here (Ch 4, Rule 7) are the most common source of wrong complexity answers. The internals behind every

    Chapter 9 of 113 min readOften asked in interviews

    Memorise this table. Hidden costs here (Ch 4, Rule 7) are the most common source of wrong complexity answers. The internals behind every row are explained in Collections, From the Inside.

    OperationCostNote
    arr[i], arr.lengthO(1)
    Arrays.sort(int[])O(n log n)a variant of quicksort for primitives
    Arrays.sort(Object[]), Collections.sort, list.sortO(n log n)a stable merge-sort variant (TimSort)
    Arrays.fill, Arrays.copyOf, clone()O(n)
    s.charAt(i), s.length()O(1)
    s.substring(a, b)O(b − a)copies characters
    s + t, s.concat(t)O(len s + len t)builds a new String; O(n²) in a loop
    s.equals(t), s.indexOf(t), s.contains(t)O(n) (indexOf/contains can be O(n·m))
    s.toCharArray(), new String(chars)O(n)
    sb.append(x)amortized O(1) (per char)
    sb.insert(0, x), sb.deleteCharAt(0)O(n)shifts everything
    sb.reverse(), sb.toString()O(n)
    ArrayList.get(i), set(i, x)O(1)
    ArrayList.add(x) (at end)amortized O(1)Ch 7
    ArrayList.add(0, x), remove(0)O(n)shifts every element
    ArrayList.remove(size - 1)O(1)
    list.contains(x), indexOf(x), remove(Object)O(n)scans
    HashMap / HashSet: get, put, add, contains, removeO(1) average
    TreeMap / TreeSet: get, put, remove, floorKey, ceiling…O(log n)sorted
    ArrayDeque push/pop/offer/poll at either endO(1)stack and queue
    PriorityQueue.offer, pollO(log n)heap
    PriorityQueue.peekO(1)
    PriorityQueue.remove(Object), containsO(n)
    LinkedList.get(i)O(n)walks the list
    Collections.reverse, list.addAll(other)O(n) / O(size of other)

    The remove(0) trap, measured — emptying a 100,000-element ArrayList from the front vs the back:

    Output
    remove(0) x100k: 440.4 ms, remove(last) x100k: 4.14 ms

    Removing from the front shifts every remaining element each time: O(n) per call, O(n²) in total — about 100× slower here. For a queue, use ArrayDeque (Collections, From the Inside).

    Check yourself

    3 questions
    1

    What's the complexity of calling list.remove(0) n times on an ArrayList of size n?

    Show answer

    O(n²).

    2

    You call s.substring(0, i) inside a loop from i = 0 to n. Complexity?

    Show answer

    O(n²) — each substring copies i characters, and 0 + 1 + … + n ≈ n²/2.

    3

    map.get(key) on a HashMap vs a TreeMap?

    Show answer

    O(1) average vs O(log n).