glossary

Every word, in plain English

Stuck on a word? Each one here has a one-line meaning, a tiny example, and the chapter that teaches it properly. Type to filter, or jump by letter.

194 terms

Symbols and numbers

A

Abstract data type (ADT)

A data type defined by what it does (its operations and their rules), not by how it's built.

"A stack has push, pop and peek, last in first out" is the ADT; an array or a linked list is how you build it.

In design questions, agree the API (method names, inputs, costs) first, then choose the structures inside.

Adjacency matrix

A V × V table where m[u][v] says whether (or how heavily) u connects to v. O(V²) space.

Checking one edge is O(1), but listing a vertex's neighbours is O(V).

Good for small, dense graphs and for Floyd–Warshall; wasteful for big sparse ones.

ArrayDeque

Java's go-to stack and queue: a resizable ring buffer with O(1) (amortized) adds and removes at both ends.

As a stack: push, pop, peek (all at the front). As a queue: offer at the back, poll from the front.

Prefer it over the old Stack class, which is synchronized and built on Vector. It doesn't allow null elements.

ArrayList

also called dynamic array

A resizable array: O(1) get by index, amortized O(1) add at the end.

When it's full, Java allocates a bigger array and copies everything across. OpenJDK 17 grows it by about 1.5×; that's an implementation detail, not a promise of the spec.

That copy is rare, so add averages out to O(1). But add(0, x) or remove(0) shifts every element: O(n).

Autoboxing

Java automatically converting between a primitive and its wrapper, like int ↔ Integer.

list.add(5) boxes 5 into an Integer; int x = list.get(0); unboxes it back.

It's convenient but not free: each boxed value can be a separate object, which is slower in hot loops.

Comparing two Integers with == compares references, not values. Use .equals() or unbox first.

B

Base case

The smallest input a recursive method answers directly, without calling itself again.

For trees it's usually if (node == null) return 0;. For arrays, an empty range or one element.

Write it first. A missing base case means infinite recursion and a StackOverflowError.

Big-Omega (Ω) and Big-Theta (Θ)

Ω is a lower bound ("at least this much"); Θ is a tight bound (both O and Ω).

Any comparison sort is Ω(n log n) in the worst case. Merge sort is Θ(n log n): never better, never worse.

In interviews people usually say "O" when they mean the tight bound. That's fine, but know the difference.

Binary heap

also called min-heap · max-heap

A complete binary tree in an array where every parent is ≤ its children (min-heap) or ≥ them (max-heap).

In a min-heap the smallest item is always at index 0. Insert and remove-min are O(log n): one sift up or down a single path.

For index i: parent (i - 1) / 2, children 2i + 1 and 2i + 2. Java's PriorityQueue is one.

Binary search on the answer

Binary-search over possible answers, using a yes/no check that is monotonic.

"Minimum speed to eat all bananas in h hours": if speed s works, every faster speed works too. Search s in 1..max.

Time is O(log(range) × cost of one check).

Binary search tree (BST)

A binary tree where every node's left subtree holds smaller values and its right subtree bigger ones.

Search, insert and delete walk one path down: O(h), which is O(log n) when balanced but O(n) for a chain.

An inorder traversal of a BST gives its values in sorted order.

"Every node in the left subtree", not just the left child, must be smaller. That's the classic validation trap.

Bipartite graph

A graph whose vertices split into two groups with every edge going between the groups, never inside one.

Test it by two-colouring with BFS/DFS: give each neighbour the opposite colour; a clash means not bipartite.

A graph is bipartite exactly when it has no cycle of odd length.

Bit shift (<<, >>, >>>)

Move all bits left or right. x << k multiplies by 2ᵏ (if it doesn't overflow); x >> 1 halves, rounding down.

>> keeps the sign bit, so negatives stay negative. >>> fills with 0s: the unsigned shift.

1 << 31 is already negative (it's Integer.MIN_VALUE), and 1 << 32 is 1, because an int shift uses only the count's low 5 bits. For bits 31 and up as a positive long, use 1L << i.

Bitwise operators

Operators that work on each bit of an integer: & (and), | (or), ^ (xor), ~ (not).

x & 1 is 1 when x is odd. x | (1 << i) turns bit i on; x & ~(1 << i) turns it off.

Don't confuse them with && and ||, which work on booleans and short-circuit.

C

Call stack

The stack of method calls still running. Each call gets a frame with its own parameters and local variables.

When main calls f, a frame for f is pushed on top. When f returns, its frame is popped and main continues.

Recursion is just many frames of the same method, each with its own n.

The exception stack trace you see is a printout of this stack.

Comparable

An interface that gives a class its natural order through compareTo. Integer and String have one.

a.compareTo(b) returns a negative number if a comes first, 0 if equal, positive if a comes after.

Collections.sort(list) and TreeMap use this order when you don't pass a comparator.

Comparator

An object that tells Java how to order two values, passed to sort, PriorityQueue or TreeMap.

compare(a, b) is negative when a should come first. Sort intervals by start: Arrays.sort(iv, Comparator.comparingInt(x -> x[0]));

Max-heap: new PriorityQueue<>(Comparator.reverseOrder()).

Avoid (a, b) -> a - b: the subtraction can overflow and flip the sign. Use Integer.compare(a, b).

Complete binary tree

A binary tree with every level full except maybe the last, which is filled from the left.

This shape lets a tree live in a plain array with no gaps: children of index i are at 2i + 1 and 2i + 2.

That's exactly how a binary heap is stored.

ConcurrentModificationException

Thrown (best-effort) when a collection is changed while a for-each loop is walking over it.

for (int x : list) if (x == 0) list.remove(…); will usually crash with it, even in single-threaded code.

Fix: use iterator.remove(), list.removeIf(x -> x == 0), or collect changes and apply them after the loop.

Constraints

also called input limits

The limits in a problem statement (like n ≤ 10⁵) that tell you how fast your solution must be.

A common rule of thumb is about 10⁸ simple steps per second. So n ≤ 10⁵ rules out O(n²) (10¹⁰ steps) but allows O(n log n).

n ≤ 20 hints at O(2ⁿ) (subsets); values up to 10⁹ hint that long may be needed for sums.

Counting sort

Sort small integers by counting each value, then writing them back in order: O(n + k) for values 0..k−1.

Exam marks 0–100: count each mark in an int[101], then output each mark as many times as it was counted.

Great when k is small; useless when values go up to 10⁹.

D

Depth and height

Depth: how far a node is from the root. Height: the longest path from a node down to a leaf.

Many textbooks count edges (root depth 0), while LeetCode's "maximum depth" counts nodes (a single node has depth 1). Check which one the problem wants.

Height in code: 1 + Math.max(height(left), height(right)), with null giving 0. That counts nodes; for edges, return −1 at null.

Difference array

Record many range updates in O(1) each, then rebuild the final values with one prefix-sum pass.

To add v to every index in l..r: diff[l] += v; diff[r + 1] -= v;.

After all updates, a running sum over diff gives each index's final value: O(n + number of updates).

Dijkstra's algorithm

Shortest paths from one source when no edge weight is negative, using a min-heap of distances.

Always settle the closest unsettled vertex next, then relax its edges. With a binary heap: O((V + E) log V).

In Java, skip stale heap entries: if (d > dist[u]) continue;.

One negative edge can break it; use Bellman–Ford then.

Divide and conquer

Split the problem into independent parts, solve each part recursively, then combine the answers.

Merge sort splits the array in half, sorts each half, then merges: O(n log n).

Unlike DP, the parts don't overlap, so there's nothing to cache.

Dry run

also called trace table

Running your code by hand on a tiny input, writing each variable's value after each step.

Take [2, 7, 11], target 9: write i, nums[i], and the map after every loop pass.

It catches off-by-one errors and wrong updates before the judge does. The 3D sims are dry runs you can watch.

Dynamic programming (DP)

Solve a problem by combining answers to smaller overlapping subproblems, solving each one only once.

It needs two things: the same subproblems keep coming back, and the best answer is built from best sub-answers.

Like filling an Excel sheet where each cell is a formula over cells you already filled.

Steps: define the state, write the recurrence, set the base cases, pick the fill order.

E

Edge case

An unusual input at the boundary of what's allowed, where code most often breaks.

Typical ones: empty input, one element, all equal values, negatives, duplicates, already sorted, and the maximum size.

Before coding, list two or three aloud. After coding, dry-run at least one.

Enum

A type with a fixed set of named constants, like enum Dir { UP, DOWN, LEFT, RIGHT }.

Safer than magic numbers: the compiler only accepts real values.

Enums work in switch and have values() and ordinal(). Good for states in a machine-coding round.

Euler path

A walk that uses every edge exactly once. An Euler circuit also ends where it started.

First, all edges must be in one connected piece (ignore arrows when checking). Undirected: a circuit needs every degree even; a path needs exactly 0 or 2 odd-degree vertices.

Directed: a circuit needs in-degree = out-degree at every vertex; a path also allows one start with one extra out-edge and one end with one extra in-edge.

Hierholzer's algorithm finds it in O(E). "Reconstruct Itinerary" is this problem in disguise.

Exchange argument

A way to prove a greedy choice is safe: show that swapping it into any optimal answer never makes it worse.

For meetings, take the one that ends earliest: replacing an optimal plan's first meeting with it still leaves room for the rest.

If you can't find such an argument, try to find a counter-example. If you find one, use DP.

Exponential time

Work that multiplies with every extra element, like O(2ⁿ) or O(n!). Fine only for tiny n.

Listing all subsets of n items is 2ⁿ: about a million (1,048,576) for n = 20, already too much by n = 40.

Plain recursive Fibonacci is exponential; memoization makes it O(n).

F

Fast and slow pointers

also called Floyd's cycle detection · tortoise and hare

Two pointers through a list, one moving 2 steps for every 1 step of the other.

If there is a cycle, the fast one eventually meets the slow one inside it; if not, fast reaches null.

When fast reaches the end, slow is at the middle. O(n) time, O(1) space.

Frequency map

A HashMap from each value to how many times it appears.

for (int x : nums) freq.merge(x, 1, Integer::sum);

Use it when values are big, negative or not numbers at all (like words). For a–z, a frequency array is simpler.

G

Garbage collection

The JVM automatically frees objects that no reference can reach any more.

You never call free in Java. Once nothing points to an object, the garbage collector may reclaim its memory.

Unlink a node from a list (prev.next = node.next) and, once nothing else points to it, it can be collected.

Generics

Type parameters like <T> that let one class work for many types safely: List<String>, Map<Integer, Long>.

The compiler checks the types, so List<String> can't accidentally hold an Integer.

Type arguments must be reference types (objects), so it's List<Integer>, never List<int>.

new ArrayList<>() uses the diamond <>: Java infers the type from the left side.

H

Hash collision

Two different keys landing in the same bucket of a hash table.

Collisions are normal; the table must handle them. Java's HashMap keeps colliding keys in a small list in that bucket.

Since Java 8, a bucket that grows past 8 keys becomes a small red-black tree (if the table has at least 64 buckets; otherwise the table grows instead), so a crowded bucket usually costs O(log n), not O(n).

hashCode() contract

If two objects are equals, they must return the same hashCode(). Override both or neither.

HashMap first jumps to a bucket using hashCode(), then checks keys with equals().

A class with equals but no matching hashCode gets "lost" in a HashSet: contains usually says false for an equal key.

Arrays don't override either, so an int[] key is compared by identity. Use a record, List<Integer> or a string key.

HashMap

Java's key → value table: average O(1) put, get and containsKey.

map.merge(x, 1, Integer::sum) counts; map.getOrDefault(x, 0) reads a missing key as 0.

map.computeIfAbsent(k, z -> new ArrayList<>()).add(v) builds a list per key in one line.

It promises no iteration order (small Integer keys may come out sorted, by luck). Use TreeMap or LinkedHashMap when order matters.

HashSet

A collection of unique values with average O(1) add, remove and contains. Built on a HashMap.

if (!seen.add(x)) … checks and inserts in one step: add returns false when x was already there.

Great for "have I seen this before?", like duplicates or a visited set in BFS.

Heap (memory)

The memory area where every object made with new lives, until the garbage collector frees it.

Local variables live in the method's stack frame; the objects they point to live on the heap.

Not the same thing as the heap data structure (a priority queue). Same word, two meanings.

Too many live objects gives OutOfMemoryError; too many nested calls gives StackOverflowError.

Heapify

also called build heap

Turning an unsorted array into a heap in O(n) by sifting down from the last parent to the root.

Most nodes are near the bottom and sift down only a little, so the total is O(n), not O(n log n).

In OpenJDK, new PriorityQueue<>(collection) builds its heap this way (the Javadoc doesn't promise a cost). Calling offer n times is O(n log n).

I

Implicit graph

A graph you never store: you generate a vertex's neighbours when you need them.

Word Ladder: each word is a vertex, and its neighbours are the words one letter different.

Lock combinations, puzzle boards and grid states work the same way. Keep the visited set as a HashSet of states.

In-degree and out-degree

also called degree

In a directed graph, in-degree counts edges coming in to a vertex; out-degree counts edges going out.

For a course plan, a course's in-degree is how many prerequisites it still waits for. In-degree 0 means "ready to take".

In an undirected graph there's just "degree": the number of neighbours.

In-place

Changing the input itself instead of building a new copy, using O(1) extra space.

Reversing an array by swapping a[i] and a[n - 1 - i] is in-place; copying into a new array is not.

If the problem says "in-place", the judge checks the array you were given (sometimes along with a returned length).

Integer cache

Autoboxing (Integer.valueOf) always reuses one shared object for each value from −128 to 127.

The Java spec requires this range. Values outside it are usually new objects (a JVM flag can grow the cache).

So Integer a = 100, b = 100; a == b is true (same cached object), but with 1000 it is usually false.

This is why map.get(x) == map.get(y) works in small tests and fails on big inputs.

Always compare boxed values with .equals() or Integer.compare.

Integer overflow

When a result is too big for its type, Java silently wraps around instead of throwing an error.

An int holds −2,147,483,648 to 2,147,483,647. Integer.MAX_VALUE + 1 gives Integer.MIN_VALUE.

Use long for sums of many values or products like a * b when both can be near 10⁹: (long) a * b.

Math.abs(Integer.MIN_VALUE) is still negative, because +2,147,483,648 doesn't fit in an int.

Interface

A contract: a list of methods a class promises to have. List is an interface; ArrayList implements it.

Write List<Integer> list = new ArrayList<>(); so your code depends on the contract, not one implementation.

Queue<Integer> q = new ArrayDeque<>(); lets you use only the queue methods, which keeps intent clear.

K

KMP algorithm

also called prefix function · lps array

Finds a pattern in a text in O(n + m) without ever moving backwards in the text after a mismatch.

It precomputes, for each prefix of the pattern, the longest proper prefix that is also a suffix (the lps array).

On a mismatch, the lps value says how much of the pattern is already matched, so the text pointer never moves back.

Knapsack

Pick items with weights and values to get the most value under a weight limit W.

0/1 knapsack (each item once): loop capacity from W down to the item's weight. Unbounded (reuse allowed): loop upwards.

O(n × W): fast when W is small. "Partition equal subset sum" and "target sum" are knapsacks in disguise.

L

LinkedHashMap

A HashMap that also remembers order (insertion order, or access order if you ask), using a linked list.

With accessOrder = true and an overridden removeEldestEntry, it becomes an LRU cache in a few lines.

In an interview, you may be asked to build that same LRU from a HashMap and a doubly linked list yourself.

Load factor

How full a hash table may get before it grows. Java's HashMap default is 0.75.

With the default 16 buckets, the table doubles to 32 when it holds more than 12 entries (16 × 0.75).

Growing keeps buckets short. Each resize is O(n), but rare, so put stays O(1) amortized.

log n

also called logarithm

How many times you can halve n before reaching 1. In DSA, log means log base 2.

log₂(1,024) = 10, and log₂(10⁶) is about 20. So binary search finds an item among 10 lakh in about 20 steps.

O(log n) shows up whenever each step throws away half: binary search, balanced trees, heaps.

Lower bound and upper bound

Lower bound: the first index with a value ≥ x. Upper bound: the first index with a value > x.

In [1, 2, 2, 2, 5], for x = 2: lower bound is 1, upper bound is 4, so 2 appears 4 − 1 = 3 times.

If x is bigger than everything, both return n (one past the end). Java's TreeMap.ceilingKey is a similar idea for keys.

M

Master theorem

A shortcut for the time of divide-and-conquer recursions like T(n) = a·T(n/b) + O(nᵈ).

Merge sort is T(n) = 2T(n/2) + O(n), which solves to O(n log n). Binary search is T(n) = T(n/2) + O(1): O(log n).

If you forget it, draw the recursion tree and add the work level by level. You get the same answer.

Minimax

In a two-player game, you pick the move that is best for you, assuming the opponent then picks what's worst for you.

Game DP often stores the score difference ("my total minus yours") for whatever is left, like dp[i][j] for a row of coins.

Then dp[i][j] = max(a[i] - dp[i+1][j], a[j] - dp[i][j-1]).

Monotonic deque

A deque of indices kept in sorted order of their values, giving the max (or min) of every window in O(1).

For the window maximum: pop smaller values from the back before adding, and drop the front once it leaves the window.

The front is always the current window's maximum. Total time O(n) for all windows.

Monotonic stack

A stack kept in sorted order by popping everything that breaks the order before each push.

For "next greater element": while the top is smaller than x, pop it, because x is that element's answer.

Every element is pushed and popped at most once, so the whole pass is O(n).

Multi-source BFS

A BFS that starts with many sources in the queue at once, so every cell gets its distance to the nearest one.

"Rotting oranges": put every rotten orange in the queue first; each BFS level is one minute.

Same O(V + E) as a normal BFS, instead of one BFS per source.

N

Negative cycle

A cycle whose edge weights add up to less than zero, so going around it again always gets "shorter".

With one reachable, "shortest path" has no answer: you could loop forever.

Bellman–Ford and Floyd–Warshall can detect one; Dijkstra cannot.

NullPointerException

Thrown when you use a reference that is null: call a method on it, read a field, or index it.

TreeNode left = root.left; left.val crashes when root.left is null.

In tree and list code, check if (node == null) return …; first. That line is often the base case too.

Unboxing a null Integer (from map.get(key) with a missing key) also throws it.

O

Off-by-one error

A bug where a loop or index is one too many or one too few: < vs <=, n vs n - 1.

An array of length n has indices 0 to n − 1, so for (int i = 0; i <= n; i++) reads past the end.

Fix by deciding what each bound means (inclusive or exclusive) and checking with a dry run on 1–2 elements.

Optimal solution

In interview talk, the best time and space you can reasonably reach for the problem's limits.

Usually the brute force with its slow part replaced: a nested loop becomes a HashMap lookup, a re-scan becomes a window.

"Optimal" is about the constraints. O(n log n) is fine for n = 10⁵; you don't always need O(n).

P

Palindrome

A string that reads the same forwards and backwards, like "racecar" or "abba".

Check with two pointers from both ends moving inward: O(n) time, O(1) space.

To find palindromic substrings, expand around each centre; there are 2n − 1 centres (letters and gaps).

Partition

Rearranging an array in-place so items matching a rule come first and the rest after.

Quicksort partitions around a pivot. "Move zeroes to the end" is a partition too.

Three-way partition (Dutch national flag) splits into less / equal / greater in one O(n) pass.

Pass-by-value

Java always passes a copy of the variable into a method. For objects, the copy is the reference.

Changing an int parameter never changes the caller's variable.

Passing an array copies the address, so arr[0] = 1 inside the method is seen by the caller.

But arr = new int[5] inside the method only re-points the local copy. The caller's array is untouched.

Pivot

The element a partition step compares everything against, in quicksort and quickselect.

In the common (Lomuto) partition, the pivot ends at its final sorted position: smaller items to its left, bigger to its right.

A pivot near the median splits the work evenly; a bad pivot (always the minimum) makes quicksort O(n²).

Postfix notation

also called Reverse Polish notation · RPN

Writing operators after their operands, like 3 4 +, so no brackets or precedence rules are needed.

Evaluate with a stack: push numbers; on an operator, pop two, apply it, push the result.

3 4 + 2 * means (3 + 4) × 2 = 14.

Prefix sum

An array where pre[i] is the sum of the first i elements, so any range sum is one subtraction.

For [2, 4, 1]: pre = [0, 2, 6, 7]. Sum of indices 1..2 is pre[3] - pre[1] = 7 - 2 = 5.

Build once in O(n), answer each range query in O(1). The extra leading 0 removes special cases.

Primitive type

A plain value type built into Java: int, long, double, char, boolean, byte, short, float.

A primitive holds the value itself, not a pointer to an object. int x = 5; stores the number 5 right in x.

Primitives can't be null and have no methods. Fields and array slots start at a default: 0, false, or '\u0000'.

In hot loops, int[] beats List<Integer> because there is no object per number.

Pruning

Skipping a whole branch of a search as soon as you know it can't produce a valid or better answer.

In Combination Sum with sorted candidates, stop the loop once a candidate is bigger than the remaining target.

In N-Queens, never place a queen on an attacked column or diagonal.

Q

Queue from two stacks

A queue made of an "in" stack and an "out" stack, with amortized O(1) operations.

Push onto in. To pop, if out is empty, move everything from in to out (which reverses the order), then pop out.

Each element moves at most once, so n operations cost O(n) in total.

Quickselect

Find the k-th smallest item by partitioning and recursing into only one side: O(n) on average.

After one partition, if the pivot lands at index k you're done; otherwise go left or right, never both.

Worst case is O(n²) like quicksort. A size-k heap is the safe O(n log k) alternative.

R

Row-major order

Storing a grid row by row, so cell (r, c) of a grid with cols columns is at index r * cols + c.

Lets you turn a 2D cell into one number, for a visited array or union-find, and back: r = i / cols, c = i % cols.

In Java, int[][] is an array of row arrays, so looping row by row is the natural (and cache-friendly) order.

S

Self-balancing BST

also called AVL tree · red-black tree

A BST that rotates nodes after inserts and deletes to keep its height O(log n).

AVL and red-black trees are the classic kinds. Java's TreeMap and TreeSet are red-black trees.

You'll rarely code one in an interview; you use TreeMap and explain why it's O(log n).

Sentinel node

also called dummy node · dummy head

A fake node placed before the real head, so the head never needs special-case code.

ListNode dummy = new ListNode(0); dummy.next = head; … return dummy.next;

Deleting or inserting at the front now works like anywhere else, and building a result list needs no if (head == null).

Sieve of Eratosthenes

Find all primes up to n by crossing out the multiples of each prime: O(n log log n).

Start from 2; cross out 4, 6, 8…; move to the next uncrossed number (3) and repeat.

You can start crossing at p·p, because smaller multiples were already crossed by smaller primes.

Sliding window

Keep a contiguous range [left, right] and slide it, updating its summary instead of recounting.

Fixed size k: add the element entering, remove the one leaving. Variable size: grow right, shrink left while the window breaks a rule.

Each index enters and leaves at most once, so it's O(n) even with a while inside the for.

Stable sort

A sort that keeps equal items in their original order.

Sort students by marks: with a stable sort, Rahul stays before Priya if both have 90 and he was first.

Java's Arrays.sort for objects and Collections.sort are guaranteed stable (TimSort). For primitives, Arrays.sort uses Dual-Pivot Quicksort, which is not stable, but that can't matter: equal numbers are identical.

Stack

also called LIFO

Last in, first out: you add and remove only at the top, like Ctrl+Z undoing your latest change first.

push, pop and peek are O(1). In Java use Deque<Integer> st = new ArrayDeque<>();.

Use it for matching brackets, undo history, "nearest bigger" questions, and turning recursion into a loop.

StackOverflowError

Java's error when nested calls use up all the stack space, usually recursion that never stops.

A missing or unreachable base case means every call makes another call, forever.

Even correct recursion can overflow when it goes very deep, for example DFS down a path of 10⁵ nodes.

Fix: check the base case first; for very deep inputs, switch to a loop with your own ArrayDeque.

Standard input and output

also called stdin · stdout

The text stream a program reads from (System.in) and writes to (System.out).

Online assessments often give input on stdin and compare what you print on stdout with the expected output.

On a strict judge, an extra space or a missing newline can turn a right answer into a Wrong Answer verdict.

State machine

also called finite-state machine

A small set of states plus rules for moving between them on each input character or event.

Parsing "is this a valid number?" is easier as states like sign, digits, dot, exponent than as nested ifs.

The same idea drives DP problems like stock buying with a cooldown: each day you're in a state (holding, resting…).

Static nested class

A class declared inside another with static. It doesn't need an outer object, unlike an inner class.

Helper types like static class Node { int val; Node next; } should be static nested classes.

A non-static inner class silently keeps a reference to its outer object and can't be created from static main without one.

Stress testing

Comparing your fast solution with a simple brute force on many random small inputs, to find a failing case.

Generate random arrays of size 1–8, run both, and stop at the first input where the answers differ.

That tiny failing input is much easier to debug than a hidden test case.

String pool

The JVM keeps one shared copy of each string literal, so equal literals are the same object.

"hi" == "hi" is true (same pooled object), but a string built at runtime is a new object.

So == on strings sometimes "works" and then fails on real input. Always use s.equals(t).

StringBuilder

A growable, changeable buffer of characters, for building a string piece by piece.

s += c in a loop copies the whole string every time: O(n²) for n characters.

StringBuilder sb = new StringBuilder(); sb.append(c); grows in place: O(n) in total, then sb.toString() once.

It also has reverse(), insert(), setCharAt() and deleteCharAt().

Subarray vs subsequence

A subarray must be contiguous; a subsequence keeps the order but may skip elements.

In [3, 1, 4]: [3, 1] is both; [3, 4] is a subsequence but not a subarray; [4, 3] is neither (order changed).

n elements have 2ⁿ subsequences (counting the empty one) but only n(n+1)/2 non-empty subarrays.

Subsequence problems usually need DP; subarray problems often need a window or prefix sums.

Sweep line

Turn intervals into start and end events, sort them by time, and scan left to right keeping a running count.

Meeting rooms: +1 at each start, −1 at each end; the highest running count is the number of rooms needed.

At equal times, decide which comes first (an end before a start, for touching meetings) and say it out loud.

T

Top-k with a heap

Keep the k best items with a heap of size k: O(n log k).

For the k largest, use a min-heap: push each item and pop when the size passes k. The heap's top is the k-th largest.

Like a cricket leaderboard that only keeps the top 10 scores: any new score has to beat the smallest of them.

Tree recursion

Solve a tree problem by asking both children for their answers, then combining them at the current node.

Max depth: if (node == null) return 0; return 1 + Math.max(depth(node.left), depth(node.right));

Decide two things: what each call returns, and what happens at null.

Trie

also called prefix tree

A tree of characters where each path from the root spells a prefix, so prefix lookups take O(length of word).

Contacts search on your phone: type "Pr" and every name under that path (Priya, Pranav…) is right there.

Each node has up to 26 children (TrieNode[] next = new TrieNode[26]) and an isWord flag.

U

Union-Find

also called DSU · disjoint set union

Tracks which items are in the same group, with near-O(1) find (which group?) and union (merge groups).

Each item points to a parent; the root names the group. Path compression and union by size keep trees flat.

With both, each operation is O(α(n)) amortized, where α is the inverse Ackermann function: tiny for any real n.

Great for "are these connected?" as edges keep arriving, and for Kruskal's MST.

V

Verdict (AC, WA, TLE, MLE, RE)

also called online judge

What an online judge says about your submission: Accepted, Wrong Answer, Time Limit Exceeded, Memory Limit Exceeded, Runtime Error.

WA: wrong output on some test. TLE: correct idea maybe, but too slow for the limits. RE: it crashed, like an exception.

Each verdict points to a different fix: WA → edge cases, TLE → better complexity or fast I/O, RE → nulls and bounds.

W

Worst, average and best case

The cost on the hardest input, on a typical (random) input, and on the easiest input.

Quicksort: O(n log n) on average, O(n²) in the worst case (bad pivots every time).

HashMap.get is O(1) on average; the worst case depends on collisions.

When you state a complexity, say which one you mean.

X

XOR

a ^ b sets a bit when exactly one of the two bits is 1. Equal values cancel: a ^ a = 0.

Also a ^ 0 = a, and order doesn't matter. So XOR of [4, 1, 2, 1, 2] leaves the single number 4.

That "pairs cancel" trick finds a missing or unpaired number in O(n) time and O(1) space.