← all cheatsheets

cheatsheet · after you code

Big-O of everything

Use it when: The interviewer asks "what's the complexity?", or you're comparing two approaches.

What each Java container costs

int[] (array)

read / write a[i]
O(1)
find a value
O(n)
insert / delete in the middle
O(n) (shift by hand)

ArrayList

get(i), set(i, x), size()
O(1)
add(x) at the end
amortized O(1)
add(i, x), remove(i)
O(n) (shifts the rest)
contains(x), indexOf(x)
O(n)
Java 17 docs ↗

LinkedList

add / remove at either end
O(1)
get(i)
O(n) (walks from the nearer end)
contains(x)
O(n)
Java 17 docs ↗

ArrayDeque

push, pop, offer, poll, peek (either end)
amortized O(1)
contains(x), remove(x)
O(n)
Java 17 docs ↗

HashMap / HashSet

get, put, remove, containsKey
O(1) avg
iterate everything
O(n + capacity)
Java 17 docs ↗

TreeMap / TreeSet

get, put, remove, containsKey
O(log n)
floorKey, ceilingKey, firstKey, lastKey
O(log n)
Java 17 docs ↗

PriorityQueue

offer, poll
O(log n)
peek, size
O(1)
remove(x), contains(x)
O(n)
Java 17 docs ↗

String / StringBuilder

charAt(i), length()
O(1)
substring(a, b)
O(b − a) (copies)
sb.append(x)
amortized O(length of x)
s += x inside a loop
O(n²) total: use StringBuilder

Each chapter's tables

Pick a stage, then open just the chapter you want.

01What Happens in Memory2 tables
What lives where, and for how long
Lives inFreed whenwhy
Local primitive (int i, long sum)the method's stack framethe method returnsThe value itself sits in the frame, so popping the frame frees it in O(1).
Local reference (int[] a, String s)the frame (only the arrow)the method returnsThe frame stores just the reference. The object it points at is separate.
Object or array (new int[n], new ListNode(5))the heapthe GC finds it unreachableAn object outlives the method that made it while any reference still reaches it.
Static field (static int[] memo)one copy for the whole classpractically neverWhatever a static field refers to stays alive for the whole run, across test cases.
Recursion of depth dd frames on the stackeach call returnsStack space is O(d) even when each call does O(1) work.
Everyday memory operations and their cost
TimeExtra memorywhy
Pass an array or object to a methodO(1)O(1)Only the reference is copied, never the elements.
int[] b = a;O(1)O(1)A second arrow to the same array.
a.clone() / Arrays.copyOf(a, n)O(n)O(n)A new array; every element is copied.
new int[n]O(n)O(n)The JVM fills all n slots with 0 before you see the array.
new ArrayList<>(path) snapshotO(k)O(k)k = the path's current length, paid once per saved result.
s.equals(t) vs s == tO(n) vs O(1)O(1)equals compares characters (stopping at the first difference); == compares only references.
Recursion to depth d(the calls' own work)O(d) stackOne frame per call that is still waiting for its child to return.
open this in the chapter →
02Arrays & Strings in Java3 tables
Array operations in Java
TimeExtra spacewhy
new int[n]O(n)O(n)Java fills every slot with the default value before you see it.
a[i] read / write, a.lengthO(1)O(1)Address arithmetic plus a bounds check; the length is a stored field.
Arrays.fill / equals / toStringO(n)O(1) / O(1) / O(n)One pass over the elements; toString builds a string of all of them.
Arrays.copyOf / copyOfRange / cloneO(length copied)O(length copied)A new array is allocated and filled — never a free view.
Arrays.sort(int[])O(n log n)sorts in placeDual-Pivot Quicksort; the javadoc promises O(n log n) on all data sets.
Arrays.sort(Integer[], comparator)O(n log n)up to n/2 referencesA stable merge sort (TimSort) on objects; the temp buffer is what the extra space pays for.
Arrays.asList(T[])O(1)O(1)A fixed-size List view over the same array — nothing is copied.
String and StringBuilder operations
TimeNoteswhy
s.charAt(i), s.length()O(1)read onlyThe characters sit in an internal array with a known length.
s + t (one expression)O(|s| + |t|)a new StringBoth strings are copied into a fresh one.
s += c, n times in a loopO(n²)n new StringsStep k copies k chars: 1 + 2 + … + n = n(n + 1)/2.
sb.append(c), n times, then toString()O(n)O(1) amortised per appendThe array grows to 2 × old + 2 when full, so growth copying stays under about 2n.
s.toCharArray(), s.substring(a, b)O(n), O(b − a)both copyBoth allocate new storage. substring stopped sharing the original's array in Java 7u6.
s.split(regex), s.trim()O(n)new stringsOne scan, plus a new String for every piece.
s.equals(t), s.compareTo(t)O(n)no copyChar by char until the first difference (or the end).
Integer.parseInt(s), String.valueOf(x)O(digits)parse / formatOne pass over the digits.
int[] vs Integer[] vs ArrayList<Integer>
int[]Integer[]ArrayList<Integer>why
New slots start as0null— (starts empty)Primitives default to 0; references default to null.
Memory per value (typical 64-bit JVM)4 B4 B ref + 16 B object4 B ref + 16 B object + spare capacityEach boxed value is its own object (values −128..127 are cached and shared).
Can it grow?nonoyes — add is O(1) amortisedArrays are fixed; ArrayList copies into a bigger array when full.
Sort with a Comparator?noyesyes (list.sort)Comparators work on objects only.
Main dangeroverflowNPE when unboxing nullNPE; remove(int) vs remove(Object)Boxed types bring null and reference-equality problems.
open this in the chapter →
03OOP for DSA & Design Rounds2 tables
Design choices and what they cost
Time per callMemorywhy
HashSet as an ArrayList of keysO(n)O(n)contains walks every stored key, and add/remove call it.
HashSet as boolean[10⁶ + 1]O(1)O(U), U = 10⁶ + 1One flag per possible key, used or not: the memory follows the key range, not the data.
HashSet with buckets + chainingO(1) average, O(n) worstO(n + B)A good hash spreads n keys over B buckets, so chains stay short; if every key collides, one chain holds all n.
Linked list: singly + dummy + sizeO(index)O(n)get, add and delete walk from the dummy to the position.
Linked list: doubly + two sentinelsO(min(index, n − index)); ends O(1)O(n)Walk from the nearer end; the sentinels make both ends instant.
Parking system with countersO(1)O(1)Only how many slots are free matters, not which ones.
Object basics and their cost
TimeNoteswhy
new Node(v)O(1)one heap object; fields start as 0, false or nullAllocation plus the constructor's few assignments.
Read a field / call a methodO(1)follows one referencenode.next.val is two reference hops.
Record equals / hashCode (k fields)O(k)generated from every componentEach component is compared or mixed once.
HashMap.get with a good hashCodeO(1) averagehash → bucket, then equals on a few entriesKeys are spread over many buckets.
HashMap.get when hashCode is constantO(n)every key in one bucketequals must run against keys one by one (Java 8+ tree bins help only for Comparable keys).
EnumType.values()O(k)returns a fresh copy of the constantsCache it in a static field if you call it in a loop.
open this in the chapter →
04Fast I/O, Judges & Debugging3 tables
Reading and printing n items in Java
TimeMeasured at n = 10⁶why
Scanner.nextInt() × nO(n)530 msRegex-based token matching through a 1,024-char buffer: a big constant factor.
BufferedReader + StringTokenizer + parseIntO(n)140 msPlain character scanning through an 8,192-char buffer.
StreamTokenizerO(n)217 msFast, but parses every number as a double — exact for ints, not for longs above 2⁵³.
System.out.println() × nO(n)2,478 msSystem.out flushes on every println: one write to the OS per line.
PrintWriter, flushed onceO(n)87 msLines collect in a buffer and leave in a few large writes.
StringBuilder, printed onceO(n)48 msOne string, one write.
What usually fits in a 1-second limit (rule of thumb: ~10⁸ simple steps per second)
Largest n that usually fitswhy
O(n!)n ≤ 1010! ≈ 3.6 × 10⁶ orders, each needing more work.
O(2ⁿ)n ≤ 202²⁰ ≈ 10⁶ subsets, each needing more work.
O(n³)n ≤ 500500³ = 1.25 × 10⁸.
O(n²)n ≤ 5,0005,000² = 2.5 × 10⁷; at 10⁵ it would be 10¹⁰ — hopeless.
O(n log n) or O(n)n ≤ 10⁶10⁶ × 20 = 2 × 10⁷.
O(log n) or O(1)any nlog₂ 10¹⁸ ≈ 60 steps.
Verdicts: what the judge is telling you
MeansUsual cause in Javawhy
AC — Acceptedevery test passed—Output matched on every hidden test, within the limits.
WA — Wrong Answerran fine, output differslogic bug, `int` overflow, wrong format, forgot `flush()`The program finished normally; the checker compared and disagreed.
TLE — Time Limit Exceededdidn't finish in timewrong complexity, infinite loop, Scanner/println on huge I/OThe judge stops the program at the limit, so the output is never checked.
RE — Runtime Errorcrashedindex out of bounds, null, bad parse, StackOverflowErrorAn uncaught exception or a non-zero exit code.
MLE — Memory Limit Exceededused too much memory`new int[n][n]` for big n, boxed collectionsSome judges report this as a runtime error instead.
CE — Compile Errordidn't compilewrong class name for the platform, missing importNothing ran; read the first compiler message.
open this in the chapter →
05Java Toolkit & Collections2 tables
The Collections Framework map: what each call costs
AddRemoveLookup / containsOrderwhy
ArrayListO(1) amortized at end, O(n) elsewhereO(n) (O(1) at end)get(i) O(1), contains O(n)insertionA resizable array: indexing is direct, but inserting/removing in the middle shifts elements.
LinkedListO(1) at endsO(1) at endsget(i) O(n), contains O(n)insertionDoubly linked nodes: no shifting, but reaching index i walks the list. Rarely the best choice.
ArrayDequeO(1) amortized at both endsO(1) at both endscontains O(n)insertionA circular array with a moving head: the go-to stack and queue.
HashSet / HashMapO(1) averageO(1) averageO(1) averagenoneHash to a bucket; short chains on average. Big buckets become trees (Java 8+).
LinkedHashSet / LinkedHashMapO(1) averageO(1) averageO(1) averageinsertion (or access)A HashMap plus a linked list through the entries to remember order.
TreeSet / TreeMapO(log n)O(log n)O(log n), plus floor/ceilingsortedA red-black tree: always balanced, always sorted.
PriorityQueueoffer O(log n)poll O(log n), remove(x) O(n)peek O(1), contains O(n)only the head is orderedA binary heap in an array: the minimum is at index 0; the rest is only partially ordered.
Utilities and their costs
TimeNoteswhy
Arrays.sort(int[])O(n log n)dual-pivot quicksort; primitives, so stability doesn't matterSorting primitives in place; no boxing.
Arrays.sort(T[]) / Collections.sort / list.sortO(n log n)TimSort, stable; ~O(n) on nearly sorted inputMerge-based, so equal elements keep their order. Useful for multi-key sorts.
new PriorityQueue<>(collection)O(n)heapify, cheaper than n offers (O(n log n))Builds the heap bottom-up.
Arrays.fill / copyOf / equals / toStringO(n)one passTouch every element once.
Arrays.binarySearch / Collections.binarySearchO(log n)input must already be sortedHalves the range each step (on a RandomAccess list).
String += in a loop vs StringBuilderO(n²) vs O(n)+= copies the whole string each timeStrings are immutable; StringBuilder appends are amortized O(1).
open this in the chapter →