cheatsheet · while you code
Java API by collection
Use it when: You're coding and forgot a method name, or what it costs.
Pick the collection you're using. Each call says what it does and what it costs.
| call | what it does | cost |
|---|---|---|
a.clone() / Arrays.copyOf(a, n) | Shallow copy of an array · Java Memory | O(n) |
Arrays.equals(a, b) / Arrays.deepEquals(g, h) | Compare arrays element by element (deep for 2D) · Java Memory | O(n) |
new int[n] / new int[r][c] | Zero-filled array / grid · Java Arrays & Strings | O(n) / O(r·c) |
arr.length · s.length() · list.size() | Size of an array / a String / a collection · Java Arrays & Strings | O(1) |
Arrays.fill(a, v) | Set every slot to v · Java Arrays & Strings | O(n) |
Arrays.copyOf(a, len) / copyOfRange(a, from, to) | New array; pads with 0 or null; to is exclusive · Java Arrays & Strings | O(len) |
Arrays.toString(a) / Arrays.deepToString(g) | Readable text for debugging · Java Arrays & Strings | O(n) |
Arrays.sort(a) / Arrays.sort(boxed, cmp) | Sort primitives / sort objects with a Comparator · Java Arrays & Strings | O(n log n) |
Arrays.asList(T...) | Fixed-size List view over an object array · Java Arrays & Strings | O(1) |
System.arraycopy(src, i, dst, j, len) | Fast block copy between arrays · Java Arrays & Strings | O(len) |
Arrays.sort(a) / Arrays.sort(objs, cmp) | Sort primitives / sort objects with a comparator · Java Toolkit | O(n log n) |
Arrays.toString(arr) | Readable print of an array while debugging · Mindset | O(n) |
Arrays.sort(a) | Sort an array · Big-O | O(n log n) |
Arrays.fill(memo, -1) | Mark every memo slot as "not solved yet" · Recursion | O(n) |
Arrays.binarySearch(sorted, key) | Index of key, or −(insertion point) − 1 when missing · Math & Numbers | O(log n) |
new int[n] | Fixed-size array, filled with 0 · Arrays & Strings | O(n) |
Arrays.copyOf(a, len) | Copy (and truncate or pad with 0) into a new array · Arrays & Strings | O(len) |
Arrays.sort(int[]) | In-place sort of primitives (dual-pivot quicksort) · Arrays & Strings | O(n log n) |
Arrays.equals(a, b) / Arrays.toString(a) | Compare / print contents (a == b only compares references) · Arrays & Strings | O(n) |
new int[rows][cols] | A rows × cols grid of 0s (one int[] per row) · Matrices | O(rows·cols) |
grid.length / grid[0].length | Number of rows / columns · Matrices | O(1) |
grid[r].clone() | Copy one row · Matrices | O(cols) |
Arrays.stream(grid).map(int[]::clone).toArray(int[][]::new) | Deep copy in one line · Matrices | O(rows·cols) |
Arrays.fill(grid[r], 0) | Set a whole row to one value · Matrices | O(cols) |
Arrays.deepToString(grid) / Arrays.deepEquals(a, b) | Print / compare 2D contents · Matrices | O(rows·cols) |
Arrays.sort(int[] a) | Sorts primitives in place (dual-pivot quicksort) · Two Pointers | O(n log n) |
Arrays.sort(T[] a, Comparator) | Stable sort for objects (TimSort) · Two Pointers | O(n log n) |
Arrays.copyOf(a, k) | The first k elements as a new array (handy for checking in-place answers) · Two Pointers | O(k) |
Arrays.equals(a, b) | Compare two count arrays element by element · Sliding Window | O(len) |
Arrays.binarySearch(int[] a, int key) | Index of key, or -(insertionPoint) − 1 if absent · Binary Search | O(log n) |
Arrays.binarySearch(a, from, to, key) | Same, on the range [from, to) — to is exclusive · Binary Search | O(log(to − from)) |
Arrays.binarySearch(T[] a, key, cmp) | Objects sorted by a comparator · Binary Search | O(log n) comparisons |
Arrays.sort(int[] a, from, to) | Sorts only a[from..to-1] · Sorting | O(m log m), m = to − from |
Arrays.parallelSort(a) | Multi-threaded sort for very large arrays · Sorting | O(n log n) work |
int[] best = {Integer.MIN_VALUE} | A mutable holder instead of a field · Tree Recursion | O(1) |
a == b on TreeNode | Compare nodes by reference (LCA's p and q) · Tree Recursion | O(1) |
new Node[26] | Child slots for 'a'..'z'; all start as null · Tries | O(26) to allocate |
Arrays.fill(dist, -1) | Mark every vertex "unvisited" · Graphs | O(V) |
new boolean[n] / new boolean[rows][cols] | Visited flags, all false by default · Graphs | O(V) |
Arrays.fill(dist, Integer.MAX_VALUE) | Mark every node unreached · Shortest Paths | O(V) |
dist.clone() | Snapshot for round-limited Bellman–Ford · Shortest Paths | O(V) |
int[] parent = new int[n]; parent[i] = i | Make n singleton sets · Union-Find & MST | O(n) |
Arrays.sort(edges, Comparator.comparingInt(e -> e[2])) | Sort edge rows {u, v, w} by weight (Kruskal) · Union-Find & MST | O(E log E) |
Arrays.fill(best, Integer.MAX_VALUE) | Initialise "cheapest link" array (dense Prim) · Union-Find & MST | O(n) |
int[] indegree = new int[n] | In-degree counters, all start at 0 · Topo Sort | O(n) |
Arrays.fill(color, 0) | Reset colours between test cases · Topo Sort | O(n) |
Arrays.fill(tin, -1) | Mark every vertex unvisited before a low-link DFS · Advanced Graphs | O(n) |
Arrays.sort(nums) | Sort so duplicates are adjacent and pruning can break · Backtracking | O(n log n) |
boolean[] used = new boolean[n] | Which indices are already in the path (permutations) · Backtracking | O(1) per check |
Arrays.fill(row, '.') | Initialise a board row (N-Queens, Sudoku) · Backtracking | O(n) |
Arrays.fill(a, 1) | Give every child one candy to start · Greedy | O(n) |
Arrays.sort(int[][] a, Comparator) | Stable sort of the rows (TimSort) · Intervals | O(n log n) |
new int[n + 1] | Table of n+1 zeros (index = state). Off-by-one +1 so dp[n] exists. · Dynamic Programming | O(n) |
new int[m + 1][n + 1] | 2D table, row 0 / column 0 = empty prefix · Dynamic Programming | O(m·n) |
Arrays.fill(dp, -1) | Mark every state "not computed" (or fill with a sentinel like amount + 1) · Dynamic Programming | O(n) |
new Integer[m][n] / new Boolean[n] | Memo where null = unknown (when 0 / false are real answers) · Dynamic Programming | O(m·n) |
Arrays.binarySearch(a, 0, size, x) | Index of x, or −(insertionPoint) − 1 if absent — usable for LIS patience · Dynamic Programming | O(log n) |
Arrays.stream(nums).sum() | Total of an int[] (Partition Equal Subset Sum) · Dynamic Programming | O(n) |
Arrays.fill(buy, Integer.MIN_VALUE / 2) | Start every "holding share t" state as impossible · DP Patterns | O(k) |
new boolean[m + 1][n + 1] | Two-string table; row 0 / column 0 = the empty prefix · DP Patterns | O(m·n) |
Arrays.sort(jobs, (a, b) -> Integer.compare(a[1], b[1])) | Sort int[][] rows by their end time · DP Patterns | O(n log n) |
new Integer[n][n] / new Boolean[m + 1][n + 1] | Memo where null = unknown (leads can be 0 or negative; matches can be false) · DP Patterns | O(n²) / O(m·n) |
Arrays.parallelPrefix(long[] a, Long::sum) | In-place inclusive running sums · Range Queries & Strings | O(n) |
Arrays.stream(a).distinct().sorted().toArray() | Sorted distinct values for coordinate compression · Range Queries & Strings | O(n log n) |
Arrays.binarySearch(sorted, x) | Rank of x after compression (index, ≥ 0 if present) · Range Queries & Strings | O(log n) |
a.regionMatches(i, b, j, len) | Compare two slices without substring() · Range Queries & Strings | O(len) |
| call | what it does | cost |
|---|---|---|
s.equals(t) / Objects.equals(a, b) | Compare contents (the second is null-safe) · Java Memory | O(n) for strings |
s.charAt(i) / s.toCharArray() | One char / a mutable copy of all chars · Java Arrays & Strings | O(1) / O(n) |
sb.append(x) / sb.reverse() / sb.toString() | Build, reverse and finish a string · Java Arrays & Strings | O(1) amortised / O(n) / O(n) |
String.valueOf(x) / Integer.parseInt(s) / Long.parseLong(s) | Number ↔ text · Java Arrays & Strings | O(digits) |
s.split(regex) / s.trim() / s.strip() | Cut into pieces / drop spaces at both ends · Java Arrays & Strings | O(n) |
s.equals(t) / s.compareTo(t) / s.equalsIgnoreCase(t) | Same text? / which comes first? · Java Arrays & Strings | O(n) |
Character.isDigit / isLetter / toLowerCase | Classify or normalise one char · Java Arrays & Strings | O(1) |
new StringTokenizer(line) · nextToken() / hasMoreTokens() | Split a line on whitespace, fast · I/O & Debugging | O(token) |
StringBuilder + System.out.print(sb) | Collect every line, print once · I/O & Debugging | O(total output) |
new StringBuilder().append(x).reverse().toString() | Build, reverse, finish a string · Java Toolkit | O(n) total |
Character.isLetterOrDigit(c) / toLowerCase(c) | Classify / normalise characters · Java Toolkit | O(1) |
String.valueOf(i) | int → String (Fizz Buzz) · Mindset | O(digits) |
s.substring(i, j) | Copies j − i characters into a new String · Big-O | O(j − i) |
sb.append(x) | StringBuilder append · Big-O | O(1) amortized per char |
sb.append(c) / sb.deleteCharAt(sb.length() - 1) | Make a choice and undo it while backtracking · Recursion | O(1) amortized |
s.charAt(i) / s.length() | Read one char / length · Arrays & Strings | O(1) |
s.toCharArray() | Mutable copy of the characters · Arrays & Strings | O(n) |
s.substring(a, b) | New String of chars a..b−1 · Arrays & Strings | O(b − a) |
sb.append(x) / sb.toString() | Grow a StringBuilder / produce the final String · Arrays & Strings | O(1) amortized / O(n) |
String.valueOf(char[]) / new String(char[]) | Turn a char array back into a String · Arrays & Strings | O(n) |
new StringBuilder[k] | k slots that start as null: create each builder before use · Matrices | O(k) |
new StringBuilder(s).reverse() | Reversed copy of a string · Two Pointers | O(n) |
Character.isLetterOrDigit(c) | True for letters and digits (skip punctuation) · Two Pointers | O(1) |
Character.toLowerCase(c) | Case-insensitive comparisons · Two Pointers | O(1) |
s.charAt(i) | Read one character without copying the string · Two Pointers | O(1) |
count[c - 'a']++ | Count a lowercase letter in an int[26] · Sliding Window | O(1) |
c >= '0' && c <= '9' · c - '0' | ASCII digit test, and its value 0–9 · Parsing | O(1) |
Character.isDigit(c) / isLetter(c) | Unicode-aware tests (also true for '५') · Parsing | O(1) |
s.indexOf(ch, from) | First index of ch at or after from, or −1 · Parsing | O(n) |
s.trim().split("\\s+") | Words separated by runs of whitespace (trim first) · Parsing | O(n) |
String.join(" ", words) | Join with exactly one separator · Parsing | O(total length) |
" ".repeat(k) | k spaces (Java 11+) · Parsing | O(k) |
sb.append(x) / sb.insert(i, c) | Append at the end / insert in the middle (shifts the rest) · Parsing | O(1) amortized / O(n) |
new String(chars, 0, n) | Build a String from the first n chars of a char[] · Parsing | O(n) |
out.writeUTF(s) / in.readUTF() | 2-byte length + modified UTF-8 bytes, and back · Parsing | O(len) |
sb.append(x) / s.split(",") | Write / read a serialized tree · Traversals | O(1) amortized / O(length) |
ch - 'a' | Letter → index 0..25 (char arithmetic) · Tries | O(1) |
(char) ('a' + i) | Index → letter, when rebuilding words in a DFS · Tries | O(1) |
new StringBuilder(w).reverse().toString() | A word reversed (Palindrome Pairs) · Tries | O(L) |
new String(charArray) | Turn a board row into the String LeetCode expects · Backtracking | O(n) |
s.charAt(i - 1) | The last letter of the prefix of length i (the table is shifted by one) · DP Patterns | O(1) |
"a".repeat(n) | Build long test strings quickly (Java 11+) · DP Patterns | O(n) |
sb.append(s) | Grow a StringBuilder (a file's content) without copying it every time · Design DS | O(|s|) amortized |
s.indexOf(p) / s.indexOf(p, from) | First match (from an offset); −1 if none · Range Queries & Strings | O(n·m) worst |
s.contains(p) | indexOf(p) >= 0 · Range Queries & Strings | O(n·m) worst |
s.startsWith(p, offset) | Does p occur exactly at offset? (no copy) · Range Queries & Strings | O(m) |
| call | what it does | cost |
|---|---|---|
new ArrayList<>(list) | Snapshot a list's current contents · Java Memory | O(n) |
list.removeIf(x -> …) / iterator.remove() | Remove while iterating, safely · I/O & Debugging | O(n) |
list.add(x) / list.get(i) / list.set(i, x) | ArrayList basics · Java Toolkit | O(1) amortized / O(1) / O(1) |
list.get(i) / list.set(i, x) | ArrayList random access · Big-O | O(1) |
list.add(x) | Append to ArrayList · Big-O | O(1) amortized |
list.add(0, x) / list.remove(0) | Insert/remove at the front of an ArrayList (shifts everything) · Big-O | O(n) |
list.contains(x) | Linear search · Big-O | O(n) |
list.add(i, x) / list.remove(i) | Insert / delete with shifting · Arrays & Strings | O(n) |
list.addFirst(x) / addLast(x) | Insert at either end (LinkedList is a Deque) · Linked Lists | O(1) |
list.removeFirst() / removeLast() | Remove at either end; throws if empty · Linked Lists | O(1) |
list.peekFirst() / pollFirst() | Look at / remove the head; return null if empty · Linked Lists | O(1) |
list.contains(x) / remove(Object) | Linear search by equals() · Linked Lists | O(n) |
listIterator().add(x) / .remove() | Insert / delete at the iterator's cursor · Linked Lists | O(1) |
list.stream().sorted(cmp).toList() | Sorted copy, original untouched · Sorting | O(n log n) |
path.remove(path.size() - 1) | Undo the last add on the way back (by index) · Tree Recursion | O(1) |
result.add(new ArrayList<>(path)) | Save a snapshot of the current path · Tree Recursion | O(h) |
adj.get(u).add(v) | Add an edge u→v to an adjacency list · Graphs | O(1) amortized |
List.of(u, v) | An immutable pair for the answer list · Advanced Graphs | O(1) |
path.add(x) | Choose: push onto the end of an ArrayList · Backtracking | O(1) amortized |
new ArrayList<>(path) | Snapshot the path when recording an answer · Backtracking | O(k) |
list.toArray(new int[0][]) | Turn a List<int[]> into the int[][] LeetCode expects · Intervals | O(n) |
list.set(i, x) / list.get(i) | Overwrite / read slot i · Design DS | O(1) |
list.remove(list.size() - 1) | Remove the last slot; nothing shifts · Design DS | O(1) |
list.remove(i) / list.remove(Integer.valueOf(x)) | Remove by index / by value; shifts everything after it · Design DS | O(n) |
path.split("/") | The parts between slashes; a leading "/" gives an empty first part · Design DS | O(length) |
| call | what it does | cost |
|---|---|---|
map.getOrDefault(k, 0) | Value or a default (no null unboxing) · Java Toolkit | O(1) average |
map.merge(k, 1, Integer::sum) | Count occurrences in one call · Java Toolkit | O(1) average |
map.computeIfAbsent(k, x -> new ArrayList<>()) | Get-or-create a group · Java Toolkit | O(1) average |
treeMap.floorKey(k) / ceilingKey(k) | Greatest key ≤ k / smallest key ≥ k · Java Toolkit | O(log n) |
map.get(key) | Value for key, or null if absent · Mindset | O(1) average |
map.put(key, value) | Insert or overwrite · Mindset | O(1) average |
map.containsKey(key) | Is the key present? · Mindset | O(1) average |
map.getOrDefault(key, 0) | Value or a default — perfect for counting · Mindset | O(1) average |
treeMap.get(k) / treeSet.add(x) | Sorted map/set (red-black tree) · Big-O | O(log n) |
map.get(k) / map.put(k, v) | Read / write a memo entry · Recursion | O(1) average |
map.merge(key, 1, Integer::sum) | Increment a count, creating it at 1 if missing · Sliding Window | O(1) avg |
map.remove(key) | Drop a key whose count reached 0 · Sliding Window | O(1) avg |
map.put(k, v) / map.get(k) | Insert/overwrite, or read (null if missing) · Hashing | O(1) avg |
map.computeIfAbsent(k, x -> new ArrayList<>()).add(v) | Group values under a key · Hashing | O(1) avg |
map.putIfAbsent(k, v) | Store v only if k is new; returns the old value (or null) — handy for one-to-one checks · Hashing | O(1) avg |
map.containsKey(k) / map.remove(k) | Check membership / delete · Hashing | O(1) avg |
map.entrySet() | Iterate key–value pairs together (faster than keySet + get) · Hashing | O(n + capacity) |
new HashMap<>(expected * 4 / 3 + 1) | Pre-size to avoid resizes when you know the count · Hashing | O(capacity) |
new LinkedHashMap<>(16, 0.75f, true) | HashMap + doubly linked list in access order (LRU) · Linked Lists | O(1) average |
TreeMap.ceilingKey(x) / floorKey(x) | Bound queries on map keys · Binary Search | O(log n) |
map.floorEntry(k) | TreeMap: the entry with the largest key ≤ k · Parsing | O(log size) |
Map<TreeNode, TreeNode> parent = new HashMap<>() | Parent links, so you can walk up the tree · Traversals | O(1) average |
Map<Integer, Integer> indexOf = new HashMap<>() | Value → inorder index when rebuilding a tree · Tree Recursion | O(1) average |
Map<TreeNode, TreeNode> parent | Parent pointers for an iterative LCA · Tree Recursion | O(1) average |
ids.computeIfAbsent(key, k -> ids.size() + 1) | Give a new subtree shape the next id, or return the old one · Tree Recursion | O(1) average |
map.put(k, v) / get(k) / remove(k) | Basic TreeMap operations · BST | O(log n) |
map.containsKey(k) | Membership (TreeSet: contains) · BST | O(log n) |
map.floorKey(k) / ceilingKey(k) | Greatest key ≤ k / least key ≥ k (or null) · BST | O(log n) |
map.lowerKey(k) / higherKey(k) | Greatest key < k / least key > k (or null) — higherKey is the inorder successor · BST | O(log n) |
map.floorEntry(k) / ceilingEntry(k) | Same, but returns key and value together · BST | O(log n) |
map.firstKey() / lastKey() | Smallest / largest key (throws if empty) · BST | O(log n) |
map.pollFirstEntry() / pollLastEntry() | Remove and return the smallest / largest entry · BST | O(log n) |
map.headMap(k) / tailMap(k) / subMap(a, b) | Live views of keys < k / ≥ k / in [a, b) · BST | O(log n) to start iterating, O(k) to walk |
new TreeMap<>(Comparator.reverseOrder()) | Custom ordering · BST | O(1) to create |
map.computeIfAbsent(ch, k -> new Node()) | Get the child, creating it if missing · Tries | O(1) average |
map.get(ch) | Child or null · Tries | O(1) average |
new TreeMap<Character, Node>() | Children kept in sorted order · Tries | O(log Σ) per step |
map.putIfAbsent(x, x) | Create a singleton set for a new key (map DSU) · Union-Find & MST | O(1) average |
map.computeIfAbsent(root, k -> new TreeSet<>()).add(x) | Group members by root, sorted (Accounts Merge) · Union-Find & MST | O(1) avg + O(log k) |
map.getOrDefault(stop, List.of()) | Buses at a stop, or an empty list for a stop no bus visits · Advanced Graphs | O(1) average |
new TreeMap<Integer, Integer>() | Counts kept in key order (red-black tree) · Greedy | O(1) to build |
treeMap.firstKey() | Smallest key still present · Greedy | O(log n) |
treeMap.merge(k, v, Integer::sum) | Add a +/− event at point k · Intervals | O(log n) |
treeMap.ceilingEntry(x) | Smallest key ≥ x (or null) · Intervals | O(log n) |
map.floorEntry(key) / map.lastEntry() | TreeMap: greatest key ≤ key (or null) / the largest key · DP Patterns | O(log n) |
map.get(k) / map.containsKey(k) | Find a key's value (null if absent) / test presence · Design DS | O(1) average |
treeMap.floorEntry(t) / floorKey(t) | Entry / key with the largest key ≤ t, or null · Design DS | O(log n) |
treeMap.keySet() | The keys in sorted order (a view; copy it before returning) · Design DS | O(k) to iterate k keys |
| call | what it does | cost |
|---|---|---|
treeSet.first() / last() / pollFirst() | Min / max / remove min of a sorted set · Java Toolkit | O(log n) |
set.contains(x) / map.get(k) | HashSet / HashMap lookup · Big-O | O(1) average, O(log n) worst for large Comparable-key bins |
set.add(x) | Adds x; returns false if x was already in the window · Sliding Window | O(1) avg |
set.add(x) / set.remove(x) | Return false if x was already there / wasn't there: a free membership check · Hashing | O(1) avg |
TreeSet.ceiling(x) / floor(x) | Smallest element ≥ x / largest ≤ x (null if none) · Binary Search | O(log n) |
TreeSet.higher(x) / lower(x) | Smallest element > x / largest < x · Binary Search | O(log n) |
Set<TreeNode> seen; seen.add(x) | add returns false if x was already there — one call checks and marks · Traversals | O(1) average |
seen.merge(sum, 1, Integer::sum) | Count a prefix sum; merge with −1 to take it back · Tree Recursion | O(1) average |
set.ceiling(x) / floor(x) / higher(x) / lower(x) | TreeSet versions of the same queries · BST | O(log n) |
set.descendingSet() / map.descendingMap() | Reverse-order view · BST | O(1) to create |
treeSet.ceiling(prefix) | First stored string ≥ prefix — a trie-free prefix check · Tries | O(L log N) |
| call | what it does | cost |
|---|---|---|
deque.push / pop / peek | Stack ops on ArrayDeque (front) · Java Toolkit | O(1) amortized |
deque.offer / poll / peek | Queue ops on ArrayDeque (back in, front out) · Java Toolkit | O(1) amortized |
deque.offerLast / pollFirst | ArrayDeque at either end · Big-O | O(1) amortized |
Deque<T> st = new ArrayDeque<>() | Explicit stack to replace deep recursion · Recursion | O(1) per op (amortized) |
st.push(x) / st.pop() / st.peek() | Push, remove, look at the top · Recursion | O(1) |
deque.offerLast(x) / pollLast() | Push / pop at the back of an ArrayDeque · Sliding Window | O(1) amortized |
deque.peekFirst() / pollFirst() | Read / remove the front (the window max) · Sliding Window | O(1) |
new ArrayDeque<>() | Array-backed deque: the default stack / queue · Linked Lists | O(1) amortized ops |
Deque<Integer> st = new ArrayDeque<>() | Create an empty stack (resizable circular array) · Stacks | O(1) |
st.push(x) | Put x on top (same as addFirst) · Stacks | O(1) amortized |
st.pop() | Remove and return the top; throws NoSuchElementException if empty · Stacks | O(1) |
st.peek() | Return the top without removing it; null if empty · Stacks | O(1) |
st.poll() | Like pop(), but returns null when empty · Stacks | O(1) |
st.isEmpty() / st.size() | Check before popping / count items · Stacks | O(1) |
st.peekLast() / st.pollLast() | Look at / remove the bottom item · Stacks | O(1) |
for (int x : st) | Iterate top → bottom (use descendingIterator() for bottom → top) · Stacks | O(n) |
int[] st = new int[n]; int top = 0; | Hand-rolled int stack: st[top++] = x, st[--top] · Stacks | O(1), no boxing |
Queue<Integer> q = new ArrayDeque<>() | Default FIFO queue (resizable circular array, no nulls) · Queues | — |
q.offer(x) / q.add(x) | Add at the rear; offer returns false if a bounded queue is full, add throws IllegalStateException · Queues | O(1) amortized |
q.poll() / q.remove() | Remove the front; poll returns null when empty, remove throws NoSuchElementException · Queues | O(1) |
q.peek() / q.element() | Read the front without removing; peek returns null, element throws · Queues | O(1) |
dq.offerFirst(x) / dq.offerLast(x) | Add at the front / back of a Deque · Queues | O(1) amortized |
dq.pollFirst() / dq.pollLast() | Remove from the front / back (null if empty) · Queues | O(1) |
dq.peekFirst() / dq.peekLast() | Read either end (null if empty) · Queues | O(1) |
dq.push(x) / dq.pop() | Stack-style: addFirst / removeFirst · Queues | O(1) amortized / O(1) |
q.size() / q.isEmpty() | Element count / emptiness · Queues | O(1) |
q.contains(x) / q.remove(x) | Search or remove one element by value · Queues | O(n) |
new ArrayBlockingQueue<>(cap) | Thread-safe bounded queue (producer/consumer) · Queues | O(1) |
Deque<TreeNode> st = new ArrayDeque<>() | Stack for iterative DFS (push / pop / peek work on the head) · Traversals | O(1) amortized |
queue.offer(x) / queue.poll() | Enqueue at the rear / dequeue from the front (BFS) · Traversals | O(1) amortized / O(1) |
queue.size() / isEmpty() | Snapshot one level's width; loop condition · Traversals | O(1) |
new LinkedList<>() (as a Queue) | A queue that accepts null — needed only when nulls are data · Traversals | O(1) per offer/poll |
level.addFirst(x) / addLast(x) on a Deque | Build a zigzag level from either end · Traversals | O(1) |
Deque<TreeNode> stack = new ArrayDeque<>() | Explicit stack when the tree may be very deep · Tree Recursion | O(1) amortized |
stack.push(x) / stack.pop() | Add / remove at the head — LIFO · Graphs | O(1) |
deque.offerFirst(x) / offerLast(x) / pollFirst() | 0-1 BFS operations on ArrayDeque · Shortest Paths | O(1) amortized |
new ArrayDeque<Integer>() | Queue for Kahn (offer/poll) or stack for DFS (push/pop) · Topo Sort | O(1) amortized per op |
deque.push(x) / deque.peek() / deque.pop() | Explicit DFS stack instead of recursion · Advanced Graphs | O(1) |
deque.push(x) / deque.pop() / deque.peek() | Stack operations on an ArrayDeque (front = top) · Design DS | O(1) |
| call | what it does | cost |
|---|---|---|
pq.offer(x) / pq.poll() / pq.peek() | Heap insert / remove min / see min · Java Toolkit | O(log n) / O(log n) / O(1) |
new PriorityQueue<>() | Empty min-heap (natural order) · Heaps | O(1) |
new PriorityQueue<>(Comparator.reverseOrder()) | Max-heap · Heaps | O(1) |
new PriorityQueue<>(Comparator.comparingInt(x -> key)) | Order objects/arrays by a key · Heaps | O(1) |
new PriorityQueue<>(collection) | Heapify existing values · Heaps | O(n) |
pq.offer(x) / pq.add(x) | Insert · Heaps | O(log n) |
pq.poll() | Remove and return the min (null if empty) · Heaps | O(log n) |
pq.peek() | Look at the min (null if empty) · Heaps | O(1) |
pq.size() / isEmpty() | Count · Heaps | O(1) |
pq.remove(x) / contains(x) | Remove / find an arbitrary element · Heaps | O(n) |
pq.addAll(list) | Offers one by one · Heaps | O(m log n) |
new PriorityQueue<int[]>((a, b) -> Integer.compare(a[0], b[0])) | Min-heap of {dist, node} pairs · Shortest Paths | O(1) to create |
pq.offer(e) / pq.poll() | Push / remove the smallest · Shortest Paths | O(log n) |
pq.remove(obj) | Remove an arbitrary entry (avoid — that's why we use lazy deletion) · Shortest Paths | O(n) |
new PriorityQueue<int[]>(Comparator.comparingInt(a -> a[1])) | Min-heap of {node, weight} (Prim) · Union-Find & MST | offer/poll O(log n) |
pq.offer(x) / pq.poll() / pq.isEmpty() | Push, pop the smallest, test empty · Union-Find & MST | O(log n) / O(log n) / O(1) |
new PriorityQueue<Integer>() | Min-heap of ready vertices → smallest order · Topo Sort | O(log n) offer/poll |
new PriorityQueue<String>() | Min-heap of destinations: poll() gives the lexicographically smallest · Advanced Graphs | O(log n) offer/poll |
map.computeIfAbsent(k, x -> new PriorityQueue<>()).offer(v) | Adjacency with sorted neighbours for string vertices · Advanced Graphs | O(1) average + O(log n) |
| call | what it does | cost |
|---|---|---|
Collections.reverseOrder() | Comparator for descending order · Java Toolkit | O(1) |
Collections.reverse(list) | Reverses a List in place · Two Pointers | O(n) |
Collections.binarySearch(list, key) | Index of key, or −(insertion point) − 1 if it's missing · Two Pointers | O(log n) |
Collections.sort(list) / list.sort(cmp) | Stable sort of a List (TimSort) · Sorting | O(n log n) |
Comparator.comparingInt(f).thenComparing(g) | Sort by f, break ties with g · Sorting | O(1) per compare |
Comparator.reverseOrder() / cmp.reversed() | Descending order · Sorting | O(1) per compare |
Comparator.comparingInt(a -> a[0]) | Same comparator, more readable · Shortest Paths | O(1) |
Comparator.comparingInt(f).thenComparingInt(g) | Sort by one key, break ties by another · Intervals | O(1) per compare |
| call | what it does | cost |
|---|---|---|
Integer.MAX_VALUE / Integer.MIN_VALUE | 2³¹ − 1 and −2³¹: the int limits · Java Memory | O(1) |
Long.MAX_VALUE | 2⁶³ − 1 ≈ 9.2·10¹⁸ · Java Memory | O(1) |
(long) a * b | Multiply in 64 bits (cast first) · Java Memory | O(1) |
Math.addExact / multiplyExact / toIntExact | Throw ArithmeticException instead of wrapping · Java Memory | O(1) |
Integer.hashCode(x) | Hash of an int: the value itself · Java OOP | O(1) |
Math.floorMod(h, n) | Bucket index that is never negative · Java OOP | O(1) |
Integer.parseInt(s) / Long.parseLong(s) | Text → number; throws NumberFormatException · I/O & Debugging | O(digits) |
Math.floorMod(a, m) / Math.abs / Math.max | Non-negative modulo and friends · Java Toolkit | O(1) |
Integer.MAX_VALUE / Long.MAX_VALUE | Sentinels for min/max searches · Java Toolkit | O(1) |
new Random(seed) | Repeatable random inputs for stress tests · Mindset | O(1) per number |
Math.floorDiv(a, b) / Math.floorMod(a, b) | Division and remainder that round toward −∞ · Mindset | O(1) |
Integer.bitCount(x) | Number of 1-bits (used in K-th Symbol) · Recursion | O(1) |
Math.floorMod(x, m) | Remainder in [0, m) for m > 0, even when x is negative · Math & Numbers | O(1) |
Math.multiplyExact(a, b) / Math.addExact(a, b) | Throws ArithmeticException on int/long overflow instead of wrapping · Math & Numbers | O(1) |
Math.abs(x) | Absolute value. Careful: Math.abs(Integer.MIN_VALUE) stays negative · Math & Numbers | O(1) |
BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)) | gcd for numbers of any size · Math & Numbers | Euclid + binary GCD |
BigInteger.valueOf(a).modPow(e, m) | aᵉ mod m with arbitrary-size numbers · Math & Numbers | O(log e) multiplications |
BigInteger.valueOf(a).modInverse(m) | a⁻¹ mod m for any m with gcd(a, m) = 1; throws otherwise · Math & Numbers | Extended Euclid |
new Random().nextInt(bound) | Uniform int in [0, bound); rejects a few raw values to avoid modulo bias · Math & Numbers | O(1) expected |
Long.toString(x) / ch - '0' | Digits as text / one digit character to its value · Math & Numbers | O(digits) / O(1) |
Math.floorMod(x, k) | Remainder in 0..k−1 even for negative x · Hashing | O(1) |
(p + k - 1L) / k | ⌈p / k⌉ for positive p, k, computed in long (Math.ceilDiv only arrived in Java 18 — not in Java 17) · Binary Search | O(1) |
Integer.compare(a, b) | Overflow-safe -1/0/1 comparison · Sorting | O(1) |
Math.addExact(a, b) / multiplyExact(a, b) | Throw ArithmeticException on overflow instead of wrapping · Parsing | O(1) |
Math.max(l, r) / Math.abs(l - r) | Combine the children's answers · Tree Recursion | O(1) |
Integer.MIN_VALUE | Starting value for a max when values can be negative · Tree Recursion | — |
Math.min(low[u], low[v]) | Pull a child's reach up into its parent · Advanced Graphs | O(1) |
Integer.bitCount(free) | How many options a cell still has (pick the fewest first) · Backtracking | O(1) |
Math.max(a, b) / Math.min(a, b) | Update reach, farthest, a clamp or a candy count · Greedy | O(1) |
Integer.compare(x, y) | Overflow-safe comparison for comparators · Intervals | O(1) |
Integer[] order + Arrays.sort(order, cmp) | Sort query positions by value, keeping the original order · Intervals | O(q log q) |
Integer.bitCount(x) / Long.bitCount(x) | Number of 1-bits (popcount) · Bits | O(1) |
Integer.highestOneBit(x) | Only the highest 1-bit kept (0 for 0). 12 → 8 · Bits | O(1) |
Integer.lowestOneBit(x) | Only the lowest 1-bit kept, same as x & -x. 12 → 4 · Bits | O(1) |
Integer.numberOfTrailingZeros(x) | Index of the lowest 1-bit (32 for 0) · Bits | O(1) |
Integer.numberOfLeadingZeros(x) | Zeros before the highest 1-bit. 31 − nlz(x) = floor(log₂ x) · Bits | O(1) |
Integer.reverse(x) | Reverse all 32 bits · Bits | O(1) |
Integer.toBinaryString(x) | Binary text without leading zeros (negatives show all 32 bits) · Bits | O(32) |
Integer.parseUnsignedInt(s, 2) | Parse 32 binary digits even when the first one is 1 · Bits | O(len) |
Integer.toUnsignedLong(x) | Read the bits of x as 0 … 2³²−1 · Bits | O(1) |
Integer.MIN_VALUE / 2 | −∞ for impossible states (holding before any buy); leaves room for ± a price without wrapping · DP Patterns | O(1) |
Math.max(keep, move) | Every state update: stay where you are, or arrive along an arrow · DP Patterns | O(1) |
random.nextInt(n) | A uniformly random int in [0, n) · Design DS | O(1) |
| call | what it does | cost |
|---|---|---|
lo + (hi - lo) / 2 or (lo + hi) >>> 1 | Overflow-safe midpoint · Java Memory | O(1) |
x & 1 / x | 2 / x >> 1 | Read bit 0 / set bit 1 / shift bit 1 into bit 0 · Matrices | O(1) |
(1 << h) - 1 | Nodes in a perfect tree with h levels · Tree Recursion | O(1) |
(num >> b) & 1 | Bit b of num (binary trie) · Tries | O(1) |
List<List<Integer>> adj = new ArrayList<>() | Adjacency list; add n empty lists first · Topo Sort | O(1) amortized add |
mask | (1 << i), (mask >> i) & 1 | Bitmask: mark index i used / test it · Backtracking | O(1) |
free & -free, free &= free - 1 | Take the lowest free option out of a bitmask (N-Queens II, Sudoku) · Backtracking | O(1) |
new BitSet(n); set / get / clear / flip(i) | Growable bit array, one bit per index · Bits | O(1) each |
bitSet.cardinality() / nextSetBit(i) | Count the 1s / find the next 1 at or after i · Bits | O(n/64) |
i & -i / Integer.lowestOneBit(i) | Lowest set bit — the Fenwick step size · Range Queries & Strings | O(1) |
| call | what it does | cost |
|---|---|---|
new Node(v) | Allocate one object; unset fields are 0, false or null · Java OOP | O(1) |
this.field = param / this(args) | Store a constructor argument / call another constructor (first line) · Java OOP | O(1) |
o instanceof Cell other | Type check and cast in one step (Java 16+) · Java OOP | O(1) |
Objects.hash(a, b) / Objects.equals(a, b) | Quick hashCode from fields (boxes them) / null-safe equals · Java OOP | O(k) |
record P(int a, int b) {} | Immutable data class with equals, hashCode, toString · Java OOP | O(1) per new |
E.values() / e.ordinal() / E.valueOf(name) | All constants (a new array) / position / constant by name · Java OOP | O(k) / O(1) / O(1) |
new EnumMap<>(E.class) | Array-backed map keyed by enum constants · Java OOP | O(1) per operation |
Objects.hash(a, b, c) / Objects.equals(a, b) | Quick hashCode for custom keys (boxes its arguments) / null-safe equality for boxed values · Hashing | O(fields) / O(1) |
record Info(int size, int height) {} | Return several values from one recursive call · Tree Recursion | O(1) |
| call | what it does | cost |
|---|---|---|
new Scanner(System.in) · nextInt() / nextLong() / next() / nextLine() | Simple token and line reading · I/O & Debugging | O(token), large constant |
new BufferedReader(new InputStreamReader(System.in)) · readLine() | One line at a time; null at end of input · I/O & Debugging | O(line) |
new PrintWriter(new BufferedOutputStream(System.out)) · flush() | Buffered output — flush once at the end · I/O & Debugging | O(total output) |
System.err.println(x) | Debug output that stays out of stdout · I/O & Debugging | slow — delete before submitting |
assert cond : "message"; | Checked only with java -ea · I/O & Debugging | O(cost of cond) |
e.getMessage() / e.printStackTrace() | What went wrong, and where · I/O & Debugging | — |
new Thread(null, task, "deep", 1L << 26) | Run deep recursion on a thread with a bigger stack (a hint to the JVM) · Recursion | — |
java -Xss8m Main | JVM flag: bigger default thread stack size · Recursion | — |