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.
| Operation | Cost | Note |
|---|---|---|
arr[i], arr.length | O(1) | |
Arrays.sort(int[]) | O(n log n) | a variant of quicksort for primitives |
Arrays.sort(Object[]), Collections.sort, list.sort | O(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, remove | O(1) average | |
TreeMap / TreeSet: get, put, remove, floorKey, ceiling… | O(log n) | sorted |
ArrayDeque push/pop/offer/poll at either end | O(1) | stack and queue |
PriorityQueue.offer, poll | O(log n) | heap |
PriorityQueue.peek | O(1) | |
PriorityQueue.remove(Object), contains | O(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:
remove(0) x100k: 440.4 ms, remove(last) x100k: 4.14 msRemoving 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 questionsWhat's the complexity of calling list.remove(0) n times on an ArrayList of size n?
Show answerHide answer
O(n²).
You call s.substring(0, i) inside a loop from i = 0 to n. Complexity?
Show answerHide answer
O(n²) — each substring copies i characters, and 0 + 1 + … + n ≈ n²/2.
map.get(key) on a HashMap vs a TreeMap?
Show answerHide answer
O(1) average vs O(log n).