The catalog
Pick something. Watch it run.
791 concepts across 25 topics — 491 playable right now, and the rest of the roadmap ships one by one.
491
Playable now
3
Next up
297
On the roadmap
1
Free forever
Playable now
Jump straight into a visualizerBig-O / growth curve explorer
Step through n = 1 to 64 as six complexity classes race: flat lines, straight lines, and one curve that leaves the chart. Log-scaled, so even 10^19 fits.
Recursion basics (factorial, GCD)
Step through the call stack: factorial pushes frames until its base case and combines the products on the way back, while Euclid's gcd shrinks the pair with modulo until b reaches zero.
Tower of Hanoi
Move n disks between three pegs, one step at a time: watch the recursion clear the way for the largest disk, rebuild the stack on top of it, and see why the total is exactly 2^n - 1 moves.
Reverse / rotate array
reverse-rotate-array
Amortized Append (Dynamic Array)
Append into a fixed block that doubles when it fills: watch the rare O(n) copies average out to O(1) per append.
Recursion to Iteration (Explicit Stack)
Replace the call stack with a real one: push frames to descend, pop and multiply to unwind, and factorial(5) falls out.
Kadane's max subarray
Majority element (Boyer–Moore)
Majority element (Boyer–Moore)
Move zeroes / sort colors
Move zeroes / sort colors
Spiral / boundary traversal, matrix rotate
Conway's Game of Life
Palindrome & char-frequency strings
Linear search
Array Traversal Toolkit
Walk arrays and matrices on purpose: reverse from both ends, rotate by three reversals, compact zeroes with a write frontier, and spiral a grid with four moving boundaries.
Find the maximum element
One forward pass keeps the largest value seen so far.
Find the minimum element
The mirror pass: keep the smallest value seen so far.
Second largest element
Track the top two values in one pass, without sorting.
Analyze array operation trade-offs
Explain the cost of access, search, insert and delete, and when each variant wins.
Prefix maximum
Build the running tallest value from the left.
Heap sort
Suffix maximum
The same sweep from the right.
Product of array except self
Left products in one pass, running suffix product in the second, no division.
Bitwise AND / OR / XOR / shifts
Count set bits · power of two · single number
Trapping rain water with prefix and suffix bounds
Water above each wall is capped by the tallest wall on each side.
Subsets via bitmask
Left and right constraint combination
Design drill: combine two sweeps into one answer per cell.
Convert decimal to binary
Write a decimal number in binary by repeated halving.
Matrix diagonal sum
Add the main diagonal and the anti-diagonal without double-counting the centre.
Convert binary to decimal
Read a binary pattern back as a decimal number with place values.
Transpose matrix
Rows become columns; in place for squares, a new grid for rectangles.
Two Sum (hash-map approach)
Find the value of a bit pattern
State the value a bit pattern represents, width included.
Set matrix zeroes in place
Zero whole rows and columns without extra memory: mark inside the first row and column.
Group anagrams
Key each word by its sorted letters or its counts; grouping is a map of lists.
Reverse bits
Reverse the order of a 32 bit pattern, one bit per round.
Hashing Toolkit
See inside the dictionary: bucket chains and collisions, frequency maps, complement lookup for two sum, ordered-map range queries, and a two-pass string frequency scan.
Isomorphic strings
Two maps keep the shape mapping consistent in both directions.
Sort characters by frequency
Count letters, then rebuild the string in count order.
Add binary
Add two binary strings with a carry, column by column.
Happy number
A set of seen values detects the cycle of digit-square sums.
Maximum circular subarray
Max of the ordinary Kadane answer and total minus the minimum subarray.
Analyze signed two's complement representation
Explain and verify how negative numbers are stored with flip-and-add-one.
Design a simple hashmap
Buckets, a hash function and a load factor, built by hand.
Divide by powers of two using shifts
Halve numbers with right shifts and state when the sign rules bend.
Maximum product subarray
Track the best and worst product ending at each cell; negatives swap the roles.
Range bitwise AND
AND every number in a range: only the common prefix survives.
Maximum subarray sum with one deletion
Two states per cell: a run so far, and a run after one deleted value.
Fixed-size window (max sum of size K)
Two Pointers Toolkit
A family of index-walking patterns on one array: opposite ends for pair sum, read and write compaction, fast and slow for the middle, and the three-way Dutch flag partition. The name describes the family, not the count; the Dutch flag mode uses three pointers.
Longest substring without repeats
Check if the k-th bit is set
Report whether position k of a number is on.
Minimum window substring
Set the k-th bit
Turn position k on and leave the rest of the number alone.
Fruit into baskets
Trapping rain water
Move the shorter wall inward, carrying its best bound.
Clear the k-th bit
Turn position k off with the flipped mask.
Sliding Window Toolkit
Fixed frames, variable windows that repair themselves, letter-count windows for anagrams, and Kadane's extend-or-restart run for maximum subarray sums.
Toggle the k-th bit
Flip position k with one XOR.
Prefix array & range queries
Update bits in a range
Write a value into a range of positions without disturbing the neighbours.
Average of subarrays of size k
The same frame, one division per window.
Difference array
Fixed windows with rich state
Design drill: which statistics survive an add-and-drop update.
Encode feature flags
Pack several on/off features into one integer and read them back.
Design compact permission masks
Design a permission scheme over bits and justify every operation.
Minimum size subarray sum
Grow until the target is reached, shrink while it still is.
Prefix Sum Toolkit
Build once, answer forever: 1D range sums, 2D rectangle sums by inclusion-exclusion, difference-array range updates, subarray sum with a hash map, and prefix x suffix products.
Max consecutive ones III
At most k zeroes in the window; shrink while the budget is spent.
N-Queens
Place N queens on an NxN chessboard.
Check even or odd using bits
Read parity from the lowest bit.
Sudoku solver
Longest repeating character replacement
At most k non-majority characters; track the window's best count.
Counting bits
Build the set-bit counts for every number from 0 up to n.
Power of four
A power of two whose single bit sits at an even index.
Rat in a maze / word search
Permutations & subsets
Generate permutations and subsets of a collection from the same recursive template.
Minimum bit flips to convert number
Count the positions where two numbers disagree.
Knight's tour
Count excellent pairs
Count pairs whose combined OR and AND counts reach a target.
M-coloring
Missing number
Find the one value missing from the range 0 to n with XOR.
Single number III
Find the two unpaired values by splitting on a differing bit.
Generate all binary strings
Print every binary string of length n, one decision per position.
Generate all subsequences
List every subsequence of a string by taking or skipping each character.
XOR queries of a subarray
Answer subarray XOR questions from a prefix XOR array.
Fast & slow pointers (middle, cycle)
Fast & slow pointers (middle, cycle)
Letter combinations of a phone number
Build every letter string a sequence of phone digits can spell.
Find the original array of prefix XOR
Rebuild an array from its running XOR prefixes.
Maximum XOR with an element from array
Answer maximum XOR queries under a per-query limit, with a binary trie.
Generate parentheses
Print every balanced bracket string of n pairs.
Linked List Toolkit
See the memory view of a chain: walk to the tail to append, flip every next field to reverse, run fast and slow pointers to find a cycle entry, and splice two sorted chains together with a dummy sentinel.
All paths in a small decision tree
List every root to leaf path of a small decision tree.
Isolate the lowest set bit
Return the value of the lowest set bit with x & -x.
Restore IP addresses
Insert three dots so the string breaks into valid IP address parts.
Remove the lowest set bit
Clear the lowest set bit with x & (x - 1).
Enumerate all submasks
Walk every mask that fits inside a mask with s = (s - 1) & mask.
Expression add operators
Insert plus, minus and star between digits to reach a target value.
Sum over submasks
Aggregate over the submasks of every mask in about 3^n steps.
Combinations
Choose k of n items in every way, without caring about order.
Combination sum
Build every sum that reaches a target, reusing the same number as often as needed.
Subset DP transition over submasks
Split a set inside a DP transition by walking submasks.
Stack Toolkit
See last-in-first-out three ways: a driver of push, pop and peek calls against an array plus a top index, bracket matching where a closer must match the most recent opener, and the monotonic stack that answers next greater element in one pass.
Sliding window maximum (deque)
Combination sum III
Pick exactly k digits from 1 to 9 that add up to a target.
Count subsets of size k
Count the k item subsets by filtering masks with bitCount.
Maximum product of word lengths
Pair words with no shared letters for the largest length product.
Permutation sequence
Find the kth permutation in order without generating the whole list.
Merge K sorted lists
Merge k sorted chains into one sorted chain, splicing nodes rather than copying values.
Remove duplicate subset results
Generate subsets from repeated values without repeating answers.
Contains duplicate
Sort and check neighbours, or keep a seen set.
Queue & Deque Toolkit
First in, first out on three carriers plus the monotonic deque: an array queue with front and rear indices, the circular ring that reuses the cells a linear queue wastes, a deque that adds and removes at either end, and the monotonic deque behind sliding window maximum.
Find unique binary string
Produce a length n binary string that is missing from the list.
Subsets II
Generate every subset of a list with duplicates exactly once.
Permutations II
List every ordering of a list with duplicates exactly once.
Combination sum II
Reach a target with each number used at most once, from a list that has duplicates.
Serialize and deserialize a binary tree
Unique paths through duplicate choices
Count distinct results when equal choices can start identical branches.
Count nodes in a binary tree
Count every node in a binary tree.
Check palindrome pieces
Decide whether a string can split into pieces that are palindromes.
Count leaf nodes
Count the nodes that have no children.
Palindrome partitioning
Cut a string into palindromic pieces in every possible way.
Count internal nodes
Count the nodes that have at least one child.
Place numbers without repeating a column
Place one number per row so no column repeats: N-Queens without the diagonals.
N-Queens II
Count the distinct solutions of N-Queens without listing them.
Count edges in a binary tree
Count the edges of a binary tree and connect the count to the number of nodes.
Count simple grid paths
Count paths on a tiny board where no cell is reused.
Identify valid BST ordering
Given a small tree, decide whether the left smaller, right bigger rule holds everywhere.
Find subtree size
Count the nodes in the subtree rooted at a given node.
Path with obstacles and no cell reuse
Count obstacle-free paths that never step on a cell twice.
Find minimum and maximum in a BST
Walk left as far as possible for the minimum and right for the maximum.
Build a min heap
Find all ancestors of a node
List every ancestor of a given node, from the root down to its parent.
Word search II
Find every dictionary word hidden in a grid without restarting the walk for each word.
Find depth of a node
Find the depth of a node: the number of edges from the root down to it.
Search in a binary search tree
Walk down one path, comparing at every node, and return the matching node or nothing.
Kth largest element in an array
Insert into a binary search tree
Follow the search walk and hang the new value on the first empty child slot.
Find height of a binary tree
Find the height of a binary tree: the longest drop from the root to a leaf.
Find median from a data stream
Count nodes at depth K
Count how many nodes sit exactly k edges below the root.
BFS traversal of a graph
Delete node in a BST
Splice around the node in its three cases, reaching for the in-order successor when it has two children.
Find minimum in a min heap
The smallest value is always the root, so the answer is one cell away.
DFS traversal of a graph
Trim a binary search tree
Cut every value outside a given range while repairing links on the way back up.
Check full binary tree
Decide whether every node has either two children or none.
Validate a binary min heap
Every parent must be at most its children, in the tree shape or in the array that stores it.
Dijkstra's shortest path
Find parent and children in a heap array
Use the index arithmetic: children of i live at 2i+1 and 2i+2, the parent at (i-1)/2.
Check whether a binary tree is a BST
Decide whether the ordering rule holds, catching the violations that sit two levels apart.
Check complete binary tree
Decide whether the tree fills every level except the last, and fills that one from the left.
Insert into a min heap
Append at the next free cell, then sift up while the new value beats its parent.
First negative integer in every window
Report the first negative value in each window of size k.
Kth smallest element in a BST
Stop an in-order walk at the kth visit, or steer by counting nodes on the left.
Topological sort
Check perfect binary tree
Decide whether every internal node has two children and every leaf sits at the same depth.
Sliding window minimum
Find the minimum of every window of size k with increasing order candidates.
Delete minimum from a min heap
Move the last cell into the root, then sift down while a child is smaller.
Check height-balanced tree
Decide whether the two sides of every node stay within one level of each other.
Kth largest element in a BST
The mirror walk: visit the right subtree first, or count from the other end.
Kth smallest with subtree sizes
Store how many nodes each subtree holds so every step can discard a whole side.
Implement sift down
The repair walk for removals and heap building, choosing the smaller child at every step.
Longest subarray with absolute difference limit
The longest window whose biggest minus smallest value stays within a limit.
Classify a binary tree's shape
Given a tree, name its shape: full, complete, perfect, balanced, or none of these.
Choose the correct traversal
Given a task such as printing a tree, freeing it, or listing nodes at a depth, pick the traversal that fits.
In-order successor in a BST
The next larger key: the leftmost node of the right subtree, or the first ancestor that turns right.
Bellman-Ford: detect a negative cycle
Top K frequent elements
Count with a map, then keep the best K counts in a heap (or bucket them).
Preorder traversal
Visit every node in preorder: the node first, then its left subtree, then its right.
In-order predecessor in a BST
The next smaller key by the mirror rule.
Floyd-Warshall: all-pairs shortest paths
Constrained subsequence sum
Maximize a subsequence sum where chosen indices stay within k of each other.
K closest points to origin
Keep a K-sized max-heap of the closest points seen so far.
Kth largest element in a stream
Maintain a K-sized min-heap: its root is the kth largest at every moment.
Preorder traversal with a stack
Produce the preorder walk without recursion, using an explicit stack.
In-order successor with parent pointer
With parents available, climb instead of searching: the first ancestor that holds the node in its left subtree.
Merge K sorted arrays
Load the front of each array into a min-heap and always take the smallest next value.
Count vertices and edges
Read the edge list and tally the distinct vertices and the number of links.
Inorder traversal
Visit every node in inorder: the whole left subtree, then the node, then the right.
Activity selection / meeting rooms
Convert a sorted array to a BST
The middle element becomes the root; recurse on both halves to keep the tree shallow.
Fractional knapsack
Smallest range covering elements from K lists
Slide a window over the merged order: the heap gives the current minimum, a running maximum closes the range.
Balance a binary search tree
Read the tree in order, then rebuild it from the middle outward.
Inorder traversal with a stack
Produce the inorder walk with an explicit stack instead of the call stack.
Find the degree of each vertex
One pass over the edges adds one to each endpoint (both directions when edges are undirected).
Huffman coding
Identify directed vs undirected graph properties
Decide from the statement and the data whether links have a direction, and what that changes.
Find K pairs with smallest sums
Grow candidates through a heap: push the next pair from each list as the current one is taken.
AVL tree insertion
Insert like a BST, then repair the first unbalanced node on the way back with one or two rotations.
Postorder traversal
Visit every node in postorder: both subtrees first, the node last.
Jump game
Build an adjacency list
From an edge list, give every vertex the list of its neighbours.
Postorder traversal with stacks
Produce the postorder walk with stacks only.
Identify the required AVL rotation
Classify the imbalance as left-left, left-right, right-left or right-right and name its fix.
Meeting rooms II
Sort starts and keep a min-heap of end times; a room frees when its end passes.
Task scheduler
Count task kinds, then lay them out in cooling slots: the most frequent kind sets the frame.
Level-order traversal
Visit the tree row by row using a queue.
Convert an adjacency matrix to an adjacency list
One row at a time: a set cell becomes a neighbour entry.
Assign cookies
Give each child at most one cookie so the most children are satisfied.
AVL tree deletion
Delete, then rebalance on the climb home: one removal can unbalance several ancestors.
Edit Distance
Find the minimum number of operations to convert word1 to word2.
Level order with level boundaries
Group the level-order walk so every row comes out separately.
Validate red-black tree properties
Check both invariants: no red node has a red child, and every root-to-leaf path carries the same black height.
Longest Palindromic Substring
A palindrome reads the same both ways. Watch the DP table fill smallest-window-first for "babad": do the edges match, and was the inside already a palindrome?
Convert an edge list to an adjacency list
Append both endpoints to each other's lists in a single pass.
Single-threaded CPU
Sort tasks by arrival, keep a heap of available tasks by duration, and jump the clock when idle.
Lemonade change
Sell lemonade at 5 per cup and give exact change from the bills collected so far.
Red-black tree insertion
Insert red, then recolor and rotate through the standard cases until the colour rules hold again.
Find whether a path exists
Expand in rings from the source until the target appears or the frontier dries up.
Boats to save people
Carry everyone in boats that take two people, using as few boats as the weight limit allows.
All root-to-leaf paths
List every path from the root down to a leaf, carrying the current path through one walk.
Longest Palindromic Subsequence
Process tasks using servers
Two heaps: free servers by weight and busy servers by finish time, with a tie-break rule for equal weights.
Minimum depth of a binary tree
Find the shortest drop from the root down to a leaf.
Longest Common Subsequence
Candy
Hand out candy by rating, one rule for each direction, using as few pieces as possible.
Shortest path in an unweighted graph
BFS levels are distances: the first time a vertex is reached is by the fewest edges.
Red-black tree deletion
The hardest repair: the double-black case, handled with recolouring and rotations.
Diameter of a binary tree
Find the longest path between any two nodes, counted in edges.
0/1 Knapsack
Choose each item at most once to maximize total value without exceeding the weight capacity.
Non-overlapping intervals
Remove the fewest intervals so the remaining ones never overlap.
Gas station
Rotting oranges
Multi-source BFS: start from every rotten cell, advance one level per minute, count what never rots.
Minimum number of arrows to burst balloons
Burst every balloon with the fewest vertical arrows, each shot at one x position.
Maximum depth of an N-ary tree
Find the deepest level of a tree whose nodes may have any number of children.
Subset sum
Decide whether some of the values reach an exact target sum, with each value used at most once.
Word ladder
Words are vertices and one-letter changes are edges; BFS finds the shortest chain.
Minimum taps to water a garden
Water the whole garden with the fewest taps, where each tap reaches a range.
Find connected components
One DFS per unvisited vertex; each launch discovers exactly one component.
Count complete tree nodes
Count the nodes of a complete tree faster than visiting them all.
Coin change
Make an amount with the fewest coins, when each coin value may be used as many times as you like.
Climbing stairs / house robber
Binary tree maximum path sum
Find the largest sum along any path, where the path may bend at one node.
Number of islands
Grid-as-graph flood fill: each unvisited land cell starts one island walk.
Clone graph
DFS or BFS with a map from original node to its copy, so shared neighbours are copied once.
Can attend all meetings
Decide whether a person can attend every meeting without any overlap.
Longest univalue path
Find the longest run of equal values along a path between two nodes.
Longest increasing subsequence
Find the length of the longest strictly increasing subsequence of a row of numbers.
Longest zigzag path in a binary tree
Find the longest stretch that alternates left, right, left, right.
Detect cycle in an undirected graph
Track parents as you dive; an already-visited neighbour that is not the parent closes a cycle.
Stock suite (cooldown, k transactions)
Minimum platforms
Count the platforms a station needs so no train ever waits.
Distance between two nodes
Find the number of edges between two given nodes.
Is graph bipartite?
Paint the graph with two colours; an edge that meets its own colour means the answer is no.
Car pooling
Check whether a car of fixed capacity can serve every trip without ever overfilling.
Palindrome partitioning / MCM
Possible bipartition
People are vertices and dislikes are edges: two groups exist exactly when the graph is bipartite.
Sieve of Eratosthenes
Wildcard matching
Left view of a binary tree
Return the nodes visible when the binary tree is viewed from the left.
Employee free time
Find the stretches of time when every employee is free.
Job sequencing with deadlines
Schedule unit-time jobs by deadline and profit to earn the most before the deadlines pass.
Right view of a binary tree
Return the nodes visible when the binary tree is viewed from the right.
GCD / LCM (Euclid)
Two-color a graph
The colouring walk itself, tracked with a colour array and a queue or stack.
Fibonacci number
Compute the nth Fibonacci number with a table instead of a branching recursion.
Minimum cost climbing stairs
Climb one or two steps at a time, paying each visited step's cost, for the cheapest way up.
Course schedule III
Take the most courses so the total duration stays inside each course's last day.
Course schedule
Prerequisites are directed edges; a completion order exists exactly when there is no cycle.
Modular exponentiation
Left view using level-order traversal
Build the left view by walking level by level and taking the first node of each level.
Decode ways
Count how many ways a digit string can be read as letters from 1 to 26.
Pascal's triangle
Build Pascal's triangle row by row, one addition per inner entry.
Maximum number of events that can be attended
Attend the most events, at most one per day, when each event runs for one day inside a range.
Top view of a binary tree
Return the nodes visible when the binary tree is viewed from above.
Course schedule II
Produce an actual order: Kahn's queue drains zero-indegree courses, or DFS records finishing times and reverses.
Alien dictionary
Compare neighbouring words to learn letter order, topologically sort the letters, and watch the prefix trap.
Bottom view of a binary tree
Return the nodes visible when the binary tree is viewed from below.
Check if one number divides another
Decide whether one number divides another exactly.
Minimum difficulty of a job schedule
Split jobs across d days, in order, to keep the sum of each day's hardest job as small as possible.
Implement trie (insert / search / startsWith)
Russian doll envelopes
Nest the most envelopes without rotating them; both dimensions must be strictly smaller.
Pick the largest available reward
Practice the heap pattern on a simple stream: keep candidates available and always take the current best.
Network delay time
Single-source Dijkstra: the answer is the largest shortest distance, or impossible if some node never arrives.
GCD of an array
Fold Euclid across a list to find the GCD of every value.
Vertical order traversal
Group every node by horizontal position and list each position's nodes top to bottom.
Maximum profit in job scheduling
Choose non-overlapping jobs so the total pay is as large as possible.
Unique paths
Count the ways across a grid moving only right or down.
Autocomplete / search suggestions
Vertical traversal with row and column ordering
Order each column by row first, and by value when two nodes share a row.
Unique paths II
Count grid paths when some cells are blocked.
Greatest common divisor of strings
Find the largest string that repeats to build both inputs.
IPO
Start at most k projects you can afford, choosing each to grow capital as fast as possible.
Cheapest flights within K stops
The stop limit breaks plain Dijkstra: level-limited BFS over states, or Bellman-Ford run k+1 rounds.
Count common divisors
Count the numbers that divide both given values.
Minimum path sum
Find the cheapest right or down path through a grid of costs.
Build a trie from a small word list
Turn a handful of words into shared prefix paths by hand or in code.
Reorganize string
Rearrange letters so no two neighbours are the same.
Boundary traversal of a binary tree
Walk the tree's outline: left boundary, leaves left to right, right boundary.
Minimum cost to connect all points
Points are vertices and distances are weighted edges; either MST algorithm builds the cheapest network.
KMP + LPS array
Rabin–Karp rolling hash
Triangle
Find the smallest top-to-bottom path through a triangle of numbers.
Identify the lowest common ancestor
Given a small tree and two marked nodes, choose their lowest common ancestor.
Minimum operations using GCD structure
Reshape values into each other with the fewest gcd-sized steps.
Count nodes in a trie
Count one node per distinct prefix character, shared paths once.
Kruskal's minimum spanning tree
Sort edges by weight and take each one that joins two different groups, tracked with union-find.
Minimum cost to hire k workers
Hire exactly k workers so that wages keep their quality ratios fair and the bill stays minimal.
LCA when one node is an ancestor
Handle the important case where one target lies inside the other target's subtree.
Prim's minimum spanning tree
Grow one tree: always add the cheapest edge that leaves the current set, via a priority queue.
Check prime
Test one number for primality up to its square root.
Prove the earliest-finish interval choice
Write the exchange argument that the earliest-finishing interval is always safe to take first.
Dungeon game
Find the least starting health that survives a dungeon of damage and healing.
Z-algorithm
Identify shared prefix paths
Spot which prefixes several words share before writing code.
Compress a trie into shared prefix groups
Fold branchless chains into single labels to compress a dictionary.
Cherry pickup
Send two walks through a grid to collect the most cherries.
Segment tree build / query / update
Reconstruct the greedy proof for activity selection
Rebuild the swap proof for activity selection from scratch, one step at a time.
Count primes
Count the primes below a limit with a sieve.
Find first pattern occurrence
Report the first index where the pattern occurs, or minus one.
Connecting cities with minimum cost
An MST in disguise with a catch: pick the cheapest links so every city is connected, or report -1.
Closest prime numbers in range
Find the closest prime pair inside a range.
Prove Kruskal's safe edge choice
Show that the smallest edge creating no cycle can always belong to a minimum spanning tree.
Lazy propagation
Design add and search words data structure
Support word search where a dot matches any single letter.
Implement disjoint set union
Two arrays and two tricks: find with path compression, union by size or rank.
Partition equal subset sum
Split a set into two parts with equal sums, when possible.
Lowest common ancestor in a BST
Use the BST ordering rule to decide whether both targets lie left, both lie right, or split at the current node.
Count pattern occurrences
Count complete matches across the text, overlaps included.
Prime subtraction operation
Make an array strictly increasing by subtracting primes.
Fenwick tree
Target sum
Count the ways to assign plus and minus signs so the expression hits a target.
Implement trie delete
Unmark a word, then prune only the nodes nothing else needs.
Number of provinces
Each connected group is a province; union the pairs and count the remaining roots.
Lowest common ancestor with parent pointers
Find where the ancestor chains of two nodes first meet when every node has a pointer to its parent.
Find all match positions
List every starting index where the pattern occurs.
Design and prove a greedy rule
Invent a greedy rule for a custom scheduling problem and prove it safe before coding it.
Segmented sieve for a large range
Sieve the primes inside a huge interval far from 1.
Find overlapping matches
Catch matches that share characters, like aa inside aaaa.
Design a memory-efficient trie
Drop the fixed 26-slot array for a compact child structure.
Lowest common ancestor of deepest leaves
Combine subtree depths while moving upward to find the lowest node containing all deepest leaves.
Coin change II
Count the combinations of coins that make an amount.
Redundant connection
The first edge whose endpoints are already united is the one that closes the cycle.
Answer range sum by scanning
Add the cells of each range directly and know when that is enough.
Deranged Calculator
Build one expression, using only n, that returns the derangement count D(n) for every n in [2, k].
Identify static vs dynamic query problems
Classify statements by whether updates exist before solving.
Lowest common ancestor of multiple nodes
Generalize the two-node idea to find the lowest common ancestor of a set of target nodes.
Count words with a given prefix
Walk to the prefix node, then count flagged words below it.
Accounts merge
Emails are the vertices and accounts are unions of them; group the email sets under one name.
Prime factorization of a number
Write a number as a product of primes with exponents.
Compare multiple matching strategies
Run the naive scan, a rolling hash and the pattern's border table over one text, then compare what each one spent.
Ones and zeroes
Pick the largest subset of strings that fits the given limits of zeroes and ones.
Number of islands II
Grow the map cell by cell, unioning with live neighbours and tracking the island count as cells land.
Longest common prefix
Walk while each node has one child and is not a word end.
Choose the right range query structure
Match a statement's operations to the matching structure.
Profitable schemes
Count the groups of schemes that reach a profit with a bounded number of members.
Implement naive pattern matching
Try every start and compare characters until a mismatch.
Count prime factors
Count prime factors with and without multiplicity.
Serialize a binary tree
Write a binary tree as one string with markers, so the shape survives the trip.
Serialize and deserialize a BST
Write and rebuild a binary search tree using the ordering rule to drop redundant markers.
Count overlapping pattern matches
Continue at the next start after every match, never skipping.
Compare query costs
Measure build, query and update work across the candidate structures.
Distinct subsequences
Count how many ways the first string contains the second as a subsequence.
Map sum pairs
Sum the values of keys sharing a prefix, with values updating.
Find bridges in a graph
DFS with discovery times and low values: an edge is a bridge when its child cannot reach back past it.
Count divisors
Multiply (exponent + 1) over the prime factorization.
Compare naive search on different inputs
Measure how the input's shape changes the comparison count.
Design a data structure from query and update requirements
Assemble a structure from a list of operations and constraints.
Interleaving string
Decide whether a third string interleaves the other two without reordering them.
Find articulation points
The vertex version of the same walk, with the root handled by its child count.
Ranked autocomplete with frequency updates
Return top suggestions while frequencies keep changing.
Find duplicate subtrees
Give every subtree a signature while walking, and report the shapes that appear twice.
Sum of divisors
Multiply small power sums, one per prime, for the divisor sum.
Morris inorder traversal
Walk in-order with constant extra memory by borrowing each node's empty right pointer as a way back.
Word break
Decide whether a string splits into dictionary words.
Distinct prime factors of product of array
Union the prime factor sets of an array and count.
Construct a worst-case input for naive matching
Build the repeated-run shape that forces the quadratic cost.
Critical connections in a network
The same bridges, asked as a whole list: report every connection whose failure splits the network.
Range sum query - immutable
Many range sums on a fixed array: prefix sums, two reads per query.
Replace words
Replace each word by the shortest dictionary root that prefixes it.
Regular expression matching
Match a string against a pattern with dot and star.
Morris preorder traversal
Adapt the threaded walk so each node is visited on the way down instead of between its subtrees.
Compute prefix hashes
Build the fingerprint and power arrays in one forward pass.
Corporate flight bookings
Apply many booking ranges and read the per-flight totals.
Find strongly connected components
Groups where everyone reaches everyone, found by one of the two classic pass orderings.
Find shortest dictionary prefix
Stop at the first flagged node on the walk of one word.
Smallest prime factor preprocessing queries
Precompute smallest prime factors, then factor many queries fast.
Word search with a small dictionary
Grid search guided by the trie, pruning at the first missing child.
Range addition
Apply many range additions to a zero array, then read the values.
Compare equal-length substrings
Two prefix reads make each substring a comparable fingerprint.
Kosaraju's algorithm
One DFS records finishing times, the reversed graph's DFS in that order reveals the components.
Normalize a number modulo m
Bring any integer into the 0 to m − 1 range.
Recover a BST using Morris traversal
Find and fix the two swapped nodes of a broken search tree with constant extra memory.
Best time to buy and sell stock
Pick one buy day and one later sell day for the best profit.
Longest repeated substring
Find the longest substring that appears at least twice.
Best time to buy and sell stock II
Trade any number of times for the best total profit.
Modular addition and multiplication
Evaluate sums and products under a modulus without overflow.
Tarjan's strongly connected components
A single DFS with low-link values pops a component each time a cycle root closes.
Maximum path sum between two leaves
Combine the best leaf-to-node chains of both sides so the largest leaf-to-leaf path wins.
Stream of characters
Detect dictionary words ending at the newest stream position.
Insert binary numbers into a bitwise trie
One level per bit from the top down, creating missing children.
House robber III
Choose for every node between taking it and skipping its children, combining the two answers upward.
Multiple range updates and queries offline
Mix many range updates with range queries when everything is known in advance.
Detect duplicate substrings
Hash fixed-length windows into a set and watch for repeats.
Product of array except self modulo m
Multiply everything except one value, under a modulus.
Best time to buy and sell stock with cooldown
Trade with a one-day cooldown after every sale.
Substring equality queries
Answer many equality questions with prefix fingerprints.
Find best opposite-bit path for a small query
Prefer the opposite child at every level and read off the XOR.
Rank transform of an array
Replace values by ranks among their sorted distinct peers.
Best time to buy and sell stock with transaction fee
Trade any number of times while paying a fee on every transaction.
Modular prefix products
Answer range product queries modulo m.
Count good nodes in a binary tree
Carry the largest value seen on the path down so each node can test itself against it.
Binary tree cameras
Three states per node (covered, camera, uncovered) combined upward to cover the tree with the fewest cameras.
Range frequency with compressed values
Count how often a set of values appears across ranges.
Max XOR pair (bitwise trie)
Minimum cost to combine intervals
Combine small intervals at a cost per merge and pay as little as possible.
Large arithmetic expression modulo m
Evaluate a big expression with reductions at every step.
Compare fixed-length windows
Roll one fingerprint forward instead of rehashing each window.
Power of a number
Compute x^n with repeated multiplication or squaring.
Count pairs with XOR in a given range
Count pairs below each bound with subtree sizes, then subtract.
Distribute coins in a binary tree
Each subtree reports its surplus or deficit; every unit of imbalance is one move across the edge above.
Build sparse table levels
Fill the power-of-two levels of the table, one combination per cell.
Burst balloons
Burst every balloon for maximum coins, where popping rewards its neighbours.
Repeated DNA sequences
Find the ten-letter sequences that appear more than once.
Pow(x, n)
Compute x^n where n can be negative.
Maximum genetic difference query
Answer ancestor XOR queries with a trie that follows the DFS.
Minimum cost tree DP
Pick joins between growing ranges of leaf values so the total multiplied cost is smallest.
Range minimum query
Static range minima from two overlapping power-of-two blocks.
Minimum cost to cut a stick
Cut a stick at the given positions for the cheapest possible total.
Find all anagrams with hashing
Slide window fingerprints of the pattern's length.
Tree DP with rerooting
Compute each subtree's answer, then push the parent's answer down so every node can stand in as the root.
Super pow
Compute a^b where the exponent arrives as a digit array.
Range GCD query
The same two-block trick on an idempotent operation.
Longest duplicate substring
Binary search the length and test window fingerprints.
Strange printer
Print a string with a printer that may reuse the same character in one turn.
Subtree sum
Return the sum of every value in a subtree.
Many static RMQ queries
Constant time per minimum query at scale, memory included.
Find pattern with KMP
Scan once with LPS fallbacks and no backward text movement.
Count good numbers
Count digit strings by per-position choices with modular exponentiation.
Find pattern with Z
Z values equal to the pattern length mark the matches.
Huge exponent modulo m
Evaluate a power whose exponent is too large to iterate.
Range sum with blocks
Edge scans plus whole-block sums answer each range.
Repeated substring pattern
Decide whether a string repeats a shorter block.
Point update in block decomposition
Change one cell and adjust exactly one block summary.
Verify Bezout coefficients
Check whether given coefficients satisfy a×x + b×y = gcd(a, b).
Encode used items as a bitmask
Practice packing a used-set into an integer and reading it back.
Range minimum with sqrt decomposition
Block minima plus edge scans, refreshed on updates.
Longest happy prefix
The last LPS entry is the longest proper prefix that is also a suffix.
Minimum cost assignment
Assign workers to jobs one-to-one at the lowest total cost.
Extended GCD
Return the GCD with Bezout coefficients x and y.
Can I win
Decide whether the first player can force reaching a total first.
Shortest palindrome
Prepend the fewest characters to make a palindrome, via KMP matching.
Solve linear Diophantine equation
Find one integer solution of a×x + b×y = c.
Frequency queries with block decomposition
Per-block frequency tables for range counting.
Fenwick prefix sum
Walk left subtracting the lowbit until zero.
String period queries
Answer period questions from borders in the LPS array.
Count integer solutions to ax + by = c
Step through the solution family and count the ones inside bounds.
Partition to K equal sum subsets
Split a set into k parts of equal sum.
Expand around center
Find palindromes by expanding from odd and even centers.
Traveling salesman problem
Visit every city once and return for the cheapest tour.
Find modular inverse by brute force for small m
Scan multiples until one reduces to 1.
Fenwick point update
Walk right adding the lowbit through the covering ranges.
Count palindromic substrings
Count every palindromic substring in one linear pass.
Shortest path visiting all nodes
Walk a graph visiting every node in the fewest steps.
Range sum query - mutable
Range sums under point updates with a Fenwick tree or segment tree.
Modular inverse using extended Euclid
Read the inverse off the coefficient the extended algorithm returns.
Modular division
Divide under a modulus by multiplying with an inverse.
Minimum XOR sum of two arrays
Pair two arrays to minimize the sum of XORs.
Longest palindrome queries with preprocessing
Answer in-range palindrome questions from precomputed radii.
Count smaller numbers after self
Sweep from the right with a compressed Fenwick tree of seen values.
Compute nCr mod prime
One combination under a prime modulus.
Reverse pairs with compression
Count pairs where the earlier value exceeds twice the later one.
Palindrome pairs with advanced matching
Pair strings whose concatenation reads as a palindrome.
Order statistics with Fenwick tree
Rank and select queries under insertions, by binary lifting on the tree.
Inverse factorials for many combination queries
Precompute inverse factorials for constant-time nCr lookups.
Simulate failure fallback on small patterns
Walk the fallback chain by hand until an edge exists.
Build a segment tree
Leaves first, then combine upward; verify the stored summaries.
Count dictionary pattern occurrences
One automaton pass, then tally each pattern's matches.
Compute nCr for small values
Combination counts by formula or Pascal's rule.
Compute nPr
Count ordered selections with the falling chain.
Aho-Corasick pattern search
Search one text for many patterns with trie plus failure links.
Static range sum with segment tree
The three overlap cases on a tree that never changes.
Dynamic multi-pattern matching
Keep multi-pattern matching working while patterns come and go.
Dynamic range maximum with custom merge state
Store a custom state per node and merge it under updates.
Count ways to choose teams
Count team formations, labelled or not.
Simulate one lazy range update
Walk an update through the tree and park its markers.
Many nCr queries modulo prime
One precompute, then three multiplications per query.
Range addition and range sum
Lazy add markers with summaries scaled by segment length.
Find a small number matching two remainders
Meet two remainder tracks at one value.
Range assignment and range sum
Assignment markers overwrite; compose marker kinds in order.
Chinese Remainder Theorem for pairwise-coprime moduli
Build the combined answer term by term with inverses.
Multiple lazy operations with composition
Define how every pair of markers composes and push consistently.
Generalized CRT with non-coprime moduli
Merge conditions pairwise and detect contradictions.
Simulate moving range window
Stretch and shrink the window by hand, adjusting the answer per step.
Distinct values in range
Mo's algorithm with a frequency table; the count moves at zero and one.
Frequency of a value in many ranges
Per-value frequencies maintained as the window moves.
Powerful array
Running sums of frequency squared times value under window moves.
Mo's algorithm with modifications
Three pointers over left, right and time with alternating orderings.
Fundamentals & Complexity
44 concepts · 5 playableGrowth curves and the call stack — the mental models everything else builds on.
Big-O / growth curve explorer
Step through n = 1 to 64 as six complexity classes race: flat lines, straight lines, and one curve that leaves the chart. Log-scaled, so even 10^19 fits.
Recursion basics (factorial, GCD)
Step through the call stack: factorial pushes frames until its base case and combines the products on the way back, while Euclid's gcd shrinks the pair with modulo until b reaches zero.
Tower of Hanoi
Move n disks between three pegs, one step at a time: watch the recursion clear the way for the largest disk, rebuild the stack on top of it, and see why the total is exactly 2^n - 1 moves.
Amortized Append (Dynamic Array)
Append into a fixed block that doubles when it fills: watch the rare O(n) copies average out to O(1) per append.
Recursion to Iteration (Explicit Stack)
Replace the call stack with a real one: push frames to descend, pop and multiply to unwind, and factorial(5) falls out.
Identify the complexity of simple loops
Read four loop shapes and name each growth class.
Match code to Big-O
Pair snippets with their classes: constant, linear, logarithmic, quadratic.
Simplify 3n + 10
Drop constants and lower-order terms, and justify each drop.
Analyze triangular nested loops
j starts at i: count n + (n-1) + ... + 1 and name the class.
Analyze halving and doubling loops
Indices that double or halve: count the steps to the bound.
Analyze mixed sequential loops
Blocks add, nesting multiplies: combine both in one analysis.
Derive complexity from a recursive pattern
Calls, depth and branching: write the recurrence and count the total.
Analyze non-uniform nested loops
Inner loops whose bounds depend on the outer index, beyond the triangular shape.
Order the complexity classes
Sort eight classes from slowest growth to fastest.
Predict the effect of doubling n
Linear doubles, quadratic quadruples, logarithmic barely moves: apply the signatures.
Compare 100n against n squared
Decide which side wins at small n and why the verdict flips.
Find the approximate crossover point
Set two growth functions equal and solve for the crossing size.
Choose between algorithms under different input sizes
Same task, two correct solutions, three different input scales: pick per scale.
Identify the auxiliary space
Separate input space from the extra memory the algorithm adds.
Compare in-place against an extra array
Two reversal implementations and their memory bills.
Analyze recursive stack space
Count frames at the deepest point for three recursions.
Compare the two-sum time and space trade-off
Brute force against hash map: state both complexity pairs.
Analyze the peak space of divide-and-conquer
Merge sort and quicksort: total allocation against live frames at the peak.
Match input size to complexity
Given the limit, name the classes still in budget.
Eliminate impossible algorithms
Cross out approaches the constraint rules out before coding.
Estimate the work for n = 100,000
Count operations for linear, n log n and quadratic candidates.
Evaluate O(nm) from two constraints
Two limits multiply: estimate the product against the budget.
Infer the likely algorithm family from constraints
Read several limits and derive the expected pattern per one.
Track dynamic array resizes
Append by hand and record size, capacity and copies at each step.
Count total copies for doubling capacity
Sum the geometric series of copy costs and divide by the appends.
Analyze the queue built from two stacks
Each element crosses at most once: bound the total movement.
Explain monotonic stack amortization
Push once, pop at most once: total work linear despite nested loops.
Compare doubling against growing by one
Two growth policies, two total costs: derive O(n) against O(n squared).
Recursive sum
Sum n down to zero: base case, shrinking measure, combine.
Recursive Fibonacci analysis
Count the calls of the naive recursion and explain the explosion.
Reverse a string recursively
Shrink the string from both ends until the middle.
Power function
Fast exponentiation by halving the exponent and squaring the base.
Draw and analyze a recursion tree
Lay out depth, branching and work per node for a branching recursion.
Determine time and stack depth separately
Total calls and deepest stack are different numbers: report both.
Convert the recursive countdown to a loop
Nothing happens after the call, so a while loop replaces it.
Convert recursive tree preorder to iterative
Explicit stack, right child pushed before left.
Convert recursive DFS to an explicit stack
Same walk, visible pending set, visited guard kept.
Iterative postorder with explicit frames
Frames carry node and state: entering, left done, right done.
Convert backtracking recursion to manual stack state
Push decisions, pop choices, and keep the undo order intact.
Array & String
28 concepts · 25 playableIndex walking, in-place mutation, and character scans.
Reverse / rotate array
reverse-rotate-array
Kadane's max subarray
Majority element (Boyer–Moore)
Majority element (Boyer–Moore)
Move zeroes / sort colors
Move zeroes / sort colors
Spiral / boundary traversal, matrix rotate
Conway's Game of Life
Palindrome & char-frequency strings
Array Traversal Toolkit
Walk arrays and matrices on purpose: reverse from both ends, rotate by three reversals, compact zeroes with a write frontier, and spiral a grid with four moving boundaries.
Find the maximum element
One forward pass keeps the largest value seen so far.
Find the minimum element
The mirror pass: keep the smallest value seen so far.
Second largest element
Track the top two values in one pass, without sorting.
Analyze array operation trade-offs
Explain the cost of access, search, insert and delete, and when each variant wins.
Remove element
Compact the array past every occurrence of a value, in place.
Remove duplicates from a sorted array
Keep each distinct value once; write only when the value differs from the last kept.
First missing positive
Place each value at its own index by swapping, then scan for the first gap.
Prefix maximum
Build the running tallest value from the left.
Suffix maximum
The same sweep from the right.
Product of array except self
Left products in one pass, running suffix product in the second, no division.
Trapping rain water with prefix and suffix bounds
Water above each wall is capped by the tallest wall on each side.
Left and right constraint combination
Design drill: combine two sweeps into one answer per cell.
Matrix diagonal sum
Add the main diagonal and the anti-diagonal without double-counting the centre.
Transpose matrix
Rows become columns; in place for squares, a new grid for rectangles.
Set matrix zeroes in place
Zero whole rows and columns without extra memory: mark inside the first row and column.
Group anagrams
Key each word by its sorted letters or its counts; grouping is a map of lists.
Sort characters by frequency
Count letters, then rebuild the string in count order.
Maximum circular subarray
Max of the ordinary Kadane answer and total minus the minimum subarray.
Maximum product subarray
Track the best and worst product ending at each cell; negatives swap the roles.
Maximum subarray sum with one deletion
Two states per cell: a run so far, and a run after one deleted value.
Searching
40 concepts · 1 playableInterval halving made visible — the single most reused Array template.
Linear search
Binary search (+ lower/upper bound)
Rotated / nearly-sorted search
Search on answer (Koko, book allocation)
Median of two sorted arrays
Search for a value
Find a value in an unsorted array and report its absence honestly.
Search cost comparison
Compare linear and binary comparison counts on the same data.
Choose the correct search strategy
Match a statement's question shape to the right search.
Find missing search preconditions
Spot the assumptions a search needs before it applies.
Design a search strategy from constraints
Assemble a search plan from sizes, ordering and query counts.
Find the first matching value
Return the first index equal to the target and stop looking.
Find all occurrences in an array
Record every index where the target appears.
Search with a predicate
Find the first value satisfying a condition the order cannot help with.
Optimize repeated searches by preprocessing
Make a flood of searches cheaper with one preprocessing step.
Search insert position
Find where a value belongs in sorted order, present or not.
Search in an infinite sorted array
Bracket an unknown end by doubling, then halve inside it.
Find floor and ceil in a sorted array
The largest value at most the target and the smallest at least it.
Binary search with a custom monotone predicate
Write the predicate, prove the single flip, find the boundary.
Implement lower bound
The first index whose value is at least the target.
Implement upper bound
The first index whose value is strictly greater than the target.
Count occurrences in a sorted array
Upper bound minus lower bound; no scan of the run.
Find the insertion range
The range of positions where equal values would be inserted.
Boundary search over a monotone predicate
Boundary loops for any first-index-satisfying condition.
First occurrence
Save every hit and keep halving left.
Last occurrence
Save every hit and keep halving right.
Find first and last position of an element
Both ends of a run in one answer.
Frequency of a target in a sorted array
Two boundary finds replace a scan of the run.
Find a range across partitioned sorted data
Boundary searches across partition edges.
Find the rotation pivot
Where the sorted order breaks in a rotated array.
Find minimum in a rotated sorted array
The minimum sits at the rotation point; halve toward it.
Search in a rotated sorted array II
Duplicates blind the sorted-half test; shrink and retry.
Search in a fully flattened sorted matrix
Chained rows behave as one sorted array.
Search a 2D matrix
Binary search the flat index; map back by division and remainder.
Search a 2D matrix II
The top-right staircase walk retires a row or column per step.
Count values at most the target in a sorted matrix
Count what each staircase move retires.
Find the first true in a boolean array
False then true; keep the middle as a candidate on true.
Capacity to ship packages within D days
Smallest capacity whose greedy day count fits.
Minimum number of days to make m bouquets
Earliest day whose bloomed runs allow the bouquets.
Split array largest sum
Smallest sum cap achievable with the allowed number of parts.
Aggressive cows: maximize the minimum distance
Largest gap the placements can keep; place greedily to test.
Sorting
43 concepts · 2 playableCompare, swap, partition, merge — each family gets its own motion.
Bubble / selection / insertion sort
Merge sort
Quick sort (partition)
Heap sort
Counting / radix / bucket sort
Sort a small array by hand
Run one elementary sort step by step and narrate the swaps.
Identify stable vs unstable behavior
Tag equal values and check their order after the sort.
Choose a sorting algorithm from constraints
Match stability, memory and worst-case constraints to a family.
Compare sort properties
Time, memory, stability and adaptivity side by side.
Design a sort for a restricted environment
Eliminate candidates from the binding constraint down.
Implement bubble sort
Neighbour swaps with the early exit after a clean pass.
Implement selection sort
Find the minimum of the unsorted region and place it.
Implement insertion sort
Slide each value into a growing sorted prefix.
Count swaps in bubble sort
Every inversion is swapped once; count them in the loop.
Sort a nearly sorted array with insertion sort
Values near their place barely slide; measure the saving.
Analyze the best-case behavior of elementary sorts
Derive sorted-input comparison counts for all three.
Identify whether an output is stable
Compare tagged equal values against their arrival order.
Stable sort tagged values
Keep equal keys in tag order after the sort.
Multi-key sorting with stability
Least significant key first, most significant last.
Choose the stable vs in-place trade-off
Let the binding constraint pick the family.
Design a stable in-place strategy
Discuss tie-breaks by index and the cost of the guarantee.
Sort strings by length
A comparator on lengths, the algorithm untouched.
Sort pairs by first value
Compare first coordinates and decide the tie rule.
Sort intervals by end
The one-line comparator behind interval scheduling.
Largest number
Order number strings so their concatenation is maximal.
Custom object ordering
Write the order as a sentence, then as a comparator.
Comparator with multiple tie-break rules
Chain comparisons with thenComparing, most significant first.
Merge two sorted arrays
Two pointers compare fronts; ties take the left run.
Sort a linked list
Merge sort on chains: split by fast and slow pointers, then relink.
Count inversions
Count inside the merge: early right takes add the left remainder.
Partition array around a pivot
One pass grows the at-most-pivot region, then places the pivot.
Sort colors
Three zones in one pass: low, middle and high pointers.
Kth largest element
Quickselect by rank, or a size k heap for streams.
Randomized quickselect
Random pivots keep the expected depth shrinking geometrically.
Sort a nearly heap-ordered array
Decide between finishing the heap process and a cheaper pass.
Compare heap sort with quick sort under worst-case guarantees
Heap sort promises n log n everywhere; quick sort only on average.
Counting sort
Count frequencies, rebuild in value order.
Relative sort array
Emit values in the order a second array dictates, then the rest sorted.
Radix sort
A stable counting sort per digit, least significant first.
Maximum gap
Bucket by range; the answer crosses an empty bucket boundary.
Contains duplicate
Sort and check neighbours, or keep a seen set.
Minimum difference between any two values
The closest pair must be neighbours after sorting.
Merge intervals
Sort by start, then extend or close in one pass.
Divide & Conquer
9 conceptsSplit, solve, combine: the skeleton behind binary search, merge sort and quick sort.
Find the maximum by divide and conquer
Split, take each half's maximum, combine with one comparison.
Sum an array recursively by halves
Singleton base case, then add the two recursive sums.
Count recursive calls in a divide-and-conquer tree
Read the count off the tree or the recurrence.
Identify divide, solve and combine steps
Label the three beats in a given algorithm.
Derive the recurrence for a custom algorithm
Count the smaller calls and the per-call work, then read the cost.
Recursive binary search
Empty range as the base case; one surviving half per call.
Search on answer with a recursive predicate
Halve the candidate range with a passing-middle rule.
Quickselect
Partition and recurse one side; the pivot index is its rank.
Median of an unsorted array by selection
Quickselect at the middle rank, averaging two for even lengths.
Bit Manipulation
36 concepts · 36 playableUnderstand numbers as bits, manipulate individual bits, and use bit patterns to represent compact states.
Bitwise AND / OR / XOR / shifts
Count set bits · power of two · single number
Subsets via bitmask
Convert decimal to binary
Write a decimal number in binary by repeated halving.
Convert binary to decimal
Read a binary pattern back as a decimal number with place values.
Find the value of a bit pattern
State the value a bit pattern represents, width included.
Reverse bits
Reverse the order of a 32 bit pattern, one bit per round.
Add binary
Add two binary strings with a carry, column by column.
Analyze signed two's complement representation
Explain and verify how negative numbers are stored with flip-and-add-one.
Divide by powers of two using shifts
Halve numbers with right shifts and state when the sign rules bend.
Range bitwise AND
AND every number in a range: only the common prefix survives.
Check if the k-th bit is set
Report whether position k of a number is on.
Set the k-th bit
Turn position k on and leave the rest of the number alone.
Clear the k-th bit
Turn position k off with the flipped mask.
Toggle the k-th bit
Flip position k with one XOR.
Update bits in a range
Write a value into a range of positions without disturbing the neighbours.
Encode feature flags
Pack several on/off features into one integer and read them back.
Design compact permission masks
Design a permission scheme over bits and justify every operation.
Check even or odd using bits
Read parity from the lowest bit.
Counting bits
Build the set-bit counts for every number from 0 up to n.
Power of four
A power of two whose single bit sits at an even index.
Minimum bit flips to convert number
Count the positions where two numbers disagree.
Count excellent pairs
Count pairs whose combined OR and AND counts reach a target.
Missing number
Find the one value missing from the range 0 to n with XOR.
Single number III
Find the two unpaired values by splitting on a differing bit.
XOR queries of a subarray
Answer subarray XOR questions from a prefix XOR array.
Find the original array of prefix XOR
Rebuild an array from its running XOR prefixes.
Maximum XOR with an element from array
Answer maximum XOR queries under a per-query limit, with a binary trie.
Isolate the lowest set bit
Return the value of the lowest set bit with x & -x.
Remove the lowest set bit
Clear the lowest set bit with x & (x - 1).
Enumerate all submasks
Walk every mask that fits inside a mask with s = (s - 1) & mask.
Sum over submasks
Aggregate over the submasks of every mask in about 3^n steps.
Subset DP transition over submasks
Split a set inside a DP transition by walking submasks.
Count subsets of size k
Count the k item subsets by filtering masks with bitCount.
Maximum product of word lengths
Pair words with no shared letters for the largest length product.
Find unique binary string
Produce a length n binary string that is missing from the list.
Hashing
23 concepts · 5 playableBuckets, probes and collision chains.
Hash table internals (chaining, linear probing)
Two Sum (hash-map approach)
Frequency maps / anagrams
Hashing Toolkit
See inside the dictionary: bucket chains and collisions, frequency maps, complement lookup for two sum, ordered-map range queries, and a two-pass string frequency scan.
Isomorphic strings
Two maps keep the shape mapping consistent in both directions.
Happy number
A set of seen values detects the cycle of digit-square sums.
Design a simple hashmap
Buckets, a hash function and a load factor, built by hand.
Simulate separate chaining
Insert keys by hand and draw each bucket's chain.
Design a hashmap
put, get and remove over an array of buckets.
Build a toy open-addressed table
Linear probing with tombstones for deletion.
Analyze collision and load-factor behavior
Measure how chain lengths grow with the load factor and when a resize pays.
Majority element
Count one pass, or vote and confirm with Boyer-Moore.
Frequency-based rearrangement
Rearrange values so equal ones never neighbour, driven by counts.
Intersection of two arrays
One set holds the first array; the second array filters distinct hits.
Longest consecutive sequence
A set finds each run's start (no left neighbour), then counts forward.
Deduplicate under custom equality
Design drill: normalize keys before the set decides what is equal.
Two Sum IV
Pair sums in a second structure, using the complement lookup shape.
Pair sum variants
Count pairs, closest pairs and pair indices from one complement pass.
Count pairs under custom complement conditions
Count pairs whose remainder relation matches, using a stays-in-range map.
Compare map behaviors
Run identical operations on HashMap, LinkedHashMap and TreeMap and compare.
Floor and ceiling queries
Nearest key below and above, straight from an ordered map.
Ordered frequency reporting
Report counts in sorted key order; hashing counts, the tree orders.
LRU-style design with LinkedHashMap
Access order plus eviction on overflow, in a handful of lines.
Two Pointers
17 concepts · 2 playableTwo indices converging — no hash map allowed.
Two Sum (sorted input)
Container with most water
3-Sum / k-sum
Dutch national flag
Two Pointers Toolkit
A family of index-walking patterns on one array: opposite ends for pair sum, read and write compaction, fast and slow for the middle, and the three-way Dutch flag partition. The name describes the family, not the count; the Dutch flag mode uses three pointers.
Valid palindrome
Compare the two ends inward, skipping non-letters.
Squares of a sorted array
The largest square is at one end; fill the output back to front.
Trapping rain water
Move the shorter wall inward, carrying its best bound.
Remove duplicates from sorted array II
Keep each value at most twice; compare against the value two writes back.
Sort array by parity
Two pointers pin even values front and odd values back.
Stable in-place filtering
Design drill: filter while keeping the kept values in original order.
Partition array around pivot
One pass, three zones, any pivot value.
Move negative values to one side
Two zones and one swap rule, no sorting.
Three-way quickselect partition
The flag routine inside quickselect, with equal keys handled once.
3Sum closest
Fix one value and sweep for the pair nearest the remainder.
4Sum
Two layers of fix-one and the pair walk underneath.
Generic k-sum
A recursive funnel ending at the two-pointer base case.
Sliding Window
12 concepts · 10 playableA band that grows, shrinks and slides.
Fixed-size window (max sum of size K)
Longest substring without repeats
Minimum window substring
Fruit into baskets
Sliding Window Toolkit
Fixed frames, variable windows that repair themselves, letter-count windows for anagrams, and Kadane's extend-or-restart run for maximum subarray sums.
Average of subarrays of size k
The same frame, one division per window.
Fixed windows with rich state
Design drill: which statistics survive an add-and-drop update.
Minimum size subarray sum
Grow until the target is reached, shrink while it still is.
Max consecutive ones III
At most k zeroes in the window; shrink while the budget is spent.
Longest repeating character replacement
At most k non-majority characters; track the window's best count.
Identify the correct window invariant
Design drill: write the sentence each window problem maintains.
Permutation in string
Anagram scan with a fixed width and two counter updates per slide.
Prefix Sum
22 concepts · 3 playablePrecompute once, answer every range in O(1).
Prefix array & range queries
Subarray sum = K (with hash)
Difference array
2-D prefix sums / max sum rectangle
Prefix Sum Toolkit
Build once, answer forever: 1D range sums, 2D rectangle sums by inclusion-exclusion, difference-array range updates, subarray sum with a hash map, and prefix x suffix products.
Running sum of a 1D array
One pass builds the running totals in place.
Range sum query, immutable
Build the ruler once; each query is two reads and a subtraction.
Find pivot index
Left total equals right total; the right side is total minus left minus self.
Left and right sum differences
Two running totals, one pass each direction.
Multi-range static query drill
Design drill: amortize a build over many queries and prove the trade.
Apply offline range updates
Mark both ends of every range, rebuild once.
Layered range updates
Stack many overlapping additions and read the final values.
Build a 2D prefix table
The zero border and the add-add-subtract build.
Range sum query 2D, immutable
Rectangle sums from four prefix cells.
Matrix block sum
Every cell sums its local block, answered by the 2D ruler.
Count submatrices with target sum
Fix top and bottom rows, then count row-band sums with prefix hashing.
Detect a zero-sum subarray
A repeated running total means the stretch between repeats sums to zero.
Contiguous array
Rewrite the values as plus and minus one; equal-count stretches are zero sums.
Subarray sums divisible by k
Equal remainders force divisible differences; count them with a map.
Continuous subarray sum
A repeated remainder with distance at least two answers yes.
Count subarrays with XOR k
The hashing skeleton with XOR as the combine rule.
Advanced prefix-state counting
Design drill: pick the prefix algebra the question needs and count matches.
Backtracking
29 concepts · 29 playableSearch by making a choice, exploring its consequences, and undoing the choice when the branch cannot produce a valid solution.
N-Queens
Place N queens on an NxN chessboard.
Sudoku solver
Rat in a maze / word search
Permutations & subsets
Generate permutations and subsets of a collection from the same recursive template.
Knight's tour
M-coloring
Generate all binary strings
Print every binary string of length n, one decision per position.
Generate all subsequences
List every subsequence of a string by taking or skipping each character.
Letter combinations of a phone number
Build every letter string a sequence of phone digits can spell.
Generate parentheses
Print every balanced bracket string of n pairs.
All paths in a small decision tree
List every root to leaf path of a small decision tree.
Restore IP addresses
Insert three dots so the string breaks into valid IP address parts.
Expression add operators
Insert plus, minus and star between digits to reach a target value.
Combinations
Choose k of n items in every way, without caring about order.
Combination sum
Build every sum that reaches a target, reusing the same number as often as needed.
Combination sum III
Pick exactly k digits from 1 to 9 that add up to a target.
Permutation sequence
Find the kth permutation in order without generating the whole list.
Remove duplicate subset results
Generate subsets from repeated values without repeating answers.
Subsets II
Generate every subset of a list with duplicates exactly once.
Permutations II
List every ordering of a list with duplicates exactly once.
Combination sum II
Reach a target with each number used at most once, from a list that has duplicates.
Unique paths through duplicate choices
Count distinct results when equal choices can start identical branches.
Check palindrome pieces
Decide whether a string can split into pieces that are palindromes.
Palindrome partitioning
Cut a string into palindromic pieces in every possible way.
Place numbers without repeating a column
Place one number per row so no column repeats: N-Queens without the diagonals.
N-Queens II
Count the distinct solutions of N-Queens without listing them.
Count simple grid paths
Count paths on a tiny board where no cell is reused.
Path with obstacles and no cell reuse
Count obstacle-free paths that never step on a cell twice.
Word search II
Find every dictionary word hidden in a grid without restarting the walk for each word.
Linked List
59 concepts · 3 playablePointers as arrows you can actually see.
Traversal & reversal (iterative/recursive)
Fast & slow pointers (middle, cycle)
Fast & slow pointers (middle, cycle)
Merge / reorder / K-group reversal
LRU cache
Linked List Toolkit
See the memory view of a chain: walk to the tail to append, flip every next field to reverse, run fast and slow pointers to find a cycle entry, and splice two sorted chains together with a dummy sentinel.
Delete node in a linked list
Delete a node when you are given only that node, with no access to the head of the list.
Reverse a portion of the list
Reverse only the nodes between two given positions, leaving the rest of the chain in place.
Flatten a multilevel doubly linked list
Flatten a doubly linked list whose nodes can carry a child chain, so every node sits on one level.
Josephus problem
Eliminate every k-th node around a circle of people until one remains, and report the survivor.
Nth node from end
Return the node n positions from the tail, in one pass, without measuring the length first.
Merge K sorted lists
Merge k sorted chains into one sorted chain, splicing nodes rather than copying values.
Reorder list
Reorder the chain into first, last, second, second-last, and so on, in place.
Intersection of two linked lists
Find the node where two chains first share the same node, by reference, without changing either list.
Remove duplicates from a sorted list
Remove repeated values from a sorted chain so each value appears exactly once.
Palindrome linked list
Decide whether a chain reads the same forwards and backwards, in linear time with constant extra space.
Swap nodes in pairs
Swap every two adjacent nodes by rewiring links, leaving the values where they are.
Rotate list
Rotate the chain right by k places: the last k nodes move to the front, order kept.
Partition list
Reorder the chain so values below x come before values at or above x, with each group's original order kept.
Copy list with random pointer
Deep copy a chain whose nodes carry an extra random reference, so the copy shares no nodes with the original.
Traverse a linked list
Walk from the head to the end, visiting every value on the way.
Count the nodes
Count how many nodes the chain holds using one walk.
Search for a value
Find whether a value exists in the chain and where it first appears.
Nth node from the head
Return the node at position n counting from the head.
Length, iterative and recursive
Compute the length two ways and compare what each version needs.
Compare array and linked-list access costs
Explain why array[4] is arithmetic while the fourth node is a walk.
Insert at the head
Add a value in front of the chain in two writes.
Insert at the tail
Append after the last node, paying the walk or using a tail pointer.
Insert after a node
Splice a new node after one you already hold, in the safe order.
Insert at an index
Walk to the position, then splice a new node there.
Build a linked list from an array
Turn an array into a chain, one node per element.
Design a list with head and tail references
Design a linked-list type whose head and tail operations are both constant time.
Delete the head
Remove the first node by moving the head past it.
Remove linked list elements
Remove every node holding a target value in one walk.
Remove the nth node from the end
Delete a node counted from the tail without measuring the list first.
Remove duplicates from a sorted list II
Delete every node whose value appears more than once.
Reverse a linked list
Flip every arrow in one pass with three pointers.
Reverse nodes in k-group
Reverse the list in blocks of k, leaving a short tail unchanged.
Split a list into two halves
Cut the chain at the middle using two speeds.
Find the cycle length
After the meeting point, count how many nodes the loop holds.
Cycle entry distance
Reason about the distance from the head to the entry using the meeting point.
Detect a shared tail
Decide from a small diagram whether two chains share a tail.
Intersection with possible cycles
Find the first shared node when either list may contain a cycle.
Merge two sorted lists
Splice two sorted chains into one, reusing the nodes.
Sort list
Sort a linked list in n log n time without copying it into an array.
Merge in between linked lists
Replace a window of one list with a whole other list.
Alternate merge two lists
Weave two chains into one interleaved chain.
Reorder by a custom k-pattern
Reorder nodes by a repeating k-step selection instead of the classic ends-in pairing.
Traverse a doubly linked list both ways
Walk the same chain forward with next and backward with prev.
Insert and delete in a doubly linked list
Keep both directions consistent through an insert and a delete.
Design browser history
Support back and forward navigation over a visit log.
Traverse a circular linked list
Print a ring exactly once, stopping when the head returns.
Insert into a sorted circular list
Place a value in its sorted spot without breaking the ring.
Design a round-robin scheduler
Give each task one turn at a time by walking a ring.
Odd even linked list
Group the odd-indexed nodes before the even-indexed ones without creating new nodes.
Simulate LRU by hand
Run get and put calls against a small cache and show each eviction.
LFU cache
Evict the least frequently used entry, with constant-time operations.
LRU with expiration
Combine recency eviction with time-based expiry.
Clone a simple linked list
Copy a plain chain into fresh nodes.
Copy a random list with O(1) extra space
Deep-copy a chain with random pointers without a map.
Stack
29 concepts · 1 playableLIFO made visible — push and pop on the same axis.
Balanced brackets
Infix → postfix → evaluate
Monotonic stack (next greater, stock span)
Largest rectangle in histogram
Stack Toolkit
See last-in-first-out three ways: a driver of push, pop and peek calls against an array plus a top index, bracket matching where a closer must match the most recent opener, and the monotonic stack that answers next greater element in one pass.
Implement the stack operations
Build push, pop, peek and isEmpty on an array with a top index.
Reverse a string with a stack
Push every character, then pop into a new buffer to reverse it.
Remove adjacent duplicates
Cancel every pair of equal neighbouring characters in one pass.
Simplify a path
Turn a Unix-style path into its canonical form, handling dots and double dots.
Evaluate reverse Polish notation
Evaluate a postfix expression: operands push, operators pop two and push one.
Decode a repeated string
Expand an encoded string such as 3[a]2[bc] using count and string stacks.
Basic calculator II
Evaluate an expression with the four operators and no parentheses.
Basic calculator
Evaluate an expression that adds parentheses and unary minus.
Min stack
Support push, pop, top and getMin, each in constant time.
Max stack
The mirror question: constant-time push, pop, top and getMax.
Stack with minimum and maximum
Answer both extremes in constant time with one entry carrying both running values.
Design drill: aggregate metadata on a stack
Extend the metadata idea to any fold, such as a running sum, and prove pop restores the previous answer.
Next greater element I
For each element of one array, find its next greater value inside a second array.
Final prices with a discount
Give every item the first later discount at or below its price.
Daily temperatures
For each day, report how many days pass until a warmer one.
Next greater element II
Find the next greater value in a circular array with a double sweep.
Online stock span
Report the span of consecutive days at or below each new price.
Maximal rectangle
Find the largest rectangle of ones inside a binary matrix, row by row.
Sum of subarray minimums
Sum the minimum of every subarray using nearest smaller bounds per value.
Implement a queue using two stacks
Present FIFO behaviour with IN and OUT stacks and a delayed transfer.
Amortized analysis of the two-stack queue
Count element moves to prove the constant average cost honestly.
Design drill: stack interface from a queue only
Return the newest element using FIFO operations alone, by rotating the queue.
Flood fill with a stack
Repaint every connected cell using an explicit stack instead of recursion.
Design drill: simulate DFS frames
Reproduce postorder without recursion using frame markers on an explicit stack.
Queue & Deque
24 concepts · 6 playableFIFO at both ends, with the ring buffer included.
Circular queue
Sliding window maximum (deque)
First non-repeating character in a stream
Queue & Deque Toolkit
First in, first out on three carriers plus the monotonic deque: an array queue with front and rear indices, the circular ring that reuses the cells a linear queue wastes, a deque that adds and removes at either end, and the monotonic deque behind sliding window maximum.
Implement the queue operations
Build enqueue, dequeue, peek and isEmpty on a fixed array.
Design a queue with additional metadata
Report an aggregate of everything currently inside, alongside the FIFO operations.
Simulate ring-buffer indices
Walk a circular queue by hand and predict where each index lands.
Circular queue enqueue and dequeue
Run both operations on a ring with a fixed capacity.
Implement a resizable ring buffer
Grow the ring when it fills while keeping the queue order intact.
Implement the deque operations
Build all six operations: add and remove at both ends.
Use a deque as a stack and a queue
Show one structure producing both LIFO and FIFO from its end operations.
Design a circular deque
A fixed-size deque with both ends open and markers that wrap.
Palindrome check with a deque
Compare both ends of a string until they disagree or meet.
Design a custom deque with fixed memory
A hard memory limit with a documented refusal policy for both ends.
Moving average from a data stream
Report the average of the last k values after each arrival.
Number of recent calls
Count the requests seen in the last 3000 time units.
Moving sum over a stream
Maintain the sum of the last k values as the stream runs.
Design a time-window event counter
Count the events of the last t milliseconds with an explicit boundary rule.
Maintain the maximum candidate deque by hand
Run the candidate deque on a small array and see why weaker indices leave early.
First negative integer in every window
Report the first negative value in each window of size k.
Sliding window minimum
Find the minimum of every window of size k with increasing order candidates.
Longest subarray with absolute difference limit
The longest window whose biggest minus smallest value stays within a limit.
Shortest subarray with sum at least k
Prefix sums plus a monotonic deque of candidates, with negative values allowed.
Constrained subsequence sum
Maximize a subsequence sum where chosen indices stay within k of each other.
Binary Tree
65 concepts · 60 playableRecursion on a hierarchy — visits light up in order.
Traversals (in/pre/post/level, Morris)
Depth, diameter, balance check
Views (top / bottom / left / right)
LCA
Serialize and deserialize a binary tree
Count nodes in a binary tree
Count every node in a binary tree.
Count leaf nodes
Count the nodes that have no children.
Count internal nodes
Count the nodes that have at least one child.
Count edges in a binary tree
Count the edges of a binary tree and connect the count to the number of nodes.
Find subtree size
Count the nodes in the subtree rooted at a given node.
Find all ancestors of a node
List every ancestor of a given node, from the root down to its parent.
Find depth of a node
Find the depth of a node: the number of edges from the root down to it.
Find height of a binary tree
Find the height of a binary tree: the longest drop from the root to a leaf.
Count nodes at depth K
Count how many nodes sit exactly k edges below the root.
Check full binary tree
Decide whether every node has either two children or none.
Check complete binary tree
Decide whether the tree fills every level except the last, and fills that one from the left.
Check perfect binary tree
Decide whether every internal node has two children and every leaf sits at the same depth.
Check height-balanced tree
Decide whether the two sides of every node stay within one level of each other.
Classify a binary tree's shape
Given a tree, name its shape: full, complete, perfect, balanced, or none of these.
Choose the correct traversal
Given a task such as printing a tree, freeing it, or listing nodes at a depth, pick the traversal that fits.
Preorder traversal
Visit every node in preorder: the node first, then its left subtree, then its right.
Preorder traversal with a stack
Produce the preorder walk without recursion, using an explicit stack.
Inorder traversal
Visit every node in inorder: the whole left subtree, then the node, then the right.
Inorder traversal with a stack
Produce the inorder walk with an explicit stack instead of the call stack.
Postorder traversal
Visit every node in postorder: both subtrees first, the node last.
Postorder traversal with stacks
Produce the postorder walk with stacks only.
Level-order traversal
Visit the tree row by row using a queue.
Level order with level boundaries
Group the level-order walk so every row comes out separately.
All root-to-leaf paths
List every path from the root down to a leaf, carrying the current path through one walk.
Minimum depth of a binary tree
Find the shortest drop from the root down to a leaf.
Diameter of a binary tree
Find the longest path between any two nodes, counted in edges.
Maximum depth of an N-ary tree
Find the deepest level of a tree whose nodes may have any number of children.
Count complete tree nodes
Count the nodes of a complete tree faster than visiting them all.
Binary tree maximum path sum
Find the largest sum along any path, where the path may bend at one node.
Longest univalue path
Find the longest run of equal values along a path between two nodes.
Longest zigzag path in a binary tree
Find the longest stretch that alternates left, right, left, right.
Distance between two nodes
Find the number of edges between two given nodes.
Left view of a binary tree
Return the nodes visible when the binary tree is viewed from the left.
Right view of a binary tree
Return the nodes visible when the binary tree is viewed from the right.
Left view using level-order traversal
Build the left view by walking level by level and taking the first node of each level.
Top view of a binary tree
Return the nodes visible when the binary tree is viewed from above.
Bottom view of a binary tree
Return the nodes visible when the binary tree is viewed from below.
Vertical order traversal
Group every node by horizontal position and list each position's nodes top to bottom.
Vertical traversal with row and column ordering
Order each column by row first, and by value when two nodes share a row.
Boundary traversal of a binary tree
Walk the tree's outline: left boundary, leaves left to right, right boundary.
Identify the lowest common ancestor
Given a small tree and two marked nodes, choose their lowest common ancestor.
LCA when one node is an ancestor
Handle the important case where one target lies inside the other target's subtree.
Lowest common ancestor of a binary tree
Given two nodes in a binary tree, find their lowest common ancestor using recursive subtree results.
Lowest common ancestor in a BST
Use the BST ordering rule to decide whether both targets lie left, both lie right, or split at the current node.
Lowest common ancestor with parent pointers
Find where the ancestor chains of two nodes first meet when every node has a pointer to its parent.
Lowest common ancestor of deepest leaves
Combine subtree depths while moving upward to find the lowest node containing all deepest leaves.
Lowest common ancestor of multiple nodes
Generalize the two-node idea to find the lowest common ancestor of a set of target nodes.
Serialize a binary tree
Write a binary tree as one string with markers, so the shape survives the trip.
Serialize and deserialize a BST
Write and rebuild a binary search tree using the ordering rule to drop redundant markers.
Find duplicate subtrees
Give every subtree a signature while walking, and report the shapes that appear twice.
Morris inorder traversal
Walk in-order with constant extra memory by borrowing each node's empty right pointer as a way back.
Morris preorder traversal
Adapt the threaded walk so each node is visited on the way down instead of between its subtrees.
Recover a BST using Morris traversal
Find and fix the two swapped nodes of a broken search tree with constant extra memory.
Maximum path sum between two leaves
Combine the best leaf-to-node chains of both sides so the largest leaf-to-leaf path wins.
House robber III
Choose for every node between taking it and skipping its children, combining the two answers upward.
Count good nodes in a binary tree
Carry the largest value seen on the path down so each node can test itself against it.
Binary tree cameras
Three states per node (covered, camera, uncovered) combined upward to cover the tree with the fewest cameras.
Distribute coins in a binary tree
Each subtree reports its surplus or deficit; every unit of imbalance is one move across the edge above.
Minimum cost tree DP
Pick joins between growing ranges of leaf values so the total multiplied cost is smallest.
Tree DP with rerooting
Compute each subtree's answer, then push the parent's answer down so every node can stand in as the root.
Binary Search Tree
24 concepts · 21 playableOrdering invariants enforced on every operation.
Search / insert / delete
Kth smallest / floor / ceil
Build from sorted array / merge two BSTs
Identify valid BST ordering
Given a small tree, decide whether the left smaller, right bigger rule holds everywhere.
Find minimum and maximum in a BST
Walk left as far as possible for the minimum and right for the maximum.
Search in a binary search tree
Walk down one path, comparing at every node, and return the matching node or nothing.
Insert into a binary search tree
Follow the search walk and hang the new value on the first empty child slot.
Delete node in a BST
Splice around the node in its three cases, reaching for the in-order successor when it has two children.
Trim a binary search tree
Cut every value outside a given range while repairing links on the way back up.
Check whether a binary tree is a BST
Decide whether the ordering rule holds, catching the violations that sit two levels apart.
Kth smallest element in a BST
Stop an in-order walk at the kth visit, or steer by counting nodes on the left.
Kth largest element in a BST
The mirror walk: visit the right subtree first, or count from the other end.
Kth smallest with subtree sizes
Store how many nodes each subtree holds so every step can discard a whole side.
In-order successor in a BST
The next larger key: the leftmost node of the right subtree, or the first ancestor that turns right.
In-order predecessor in a BST
The next smaller key by the mirror rule.
In-order successor with parent pointer
With parents available, climb instead of searching: the first ancestor that holds the node in its left subtree.
Convert a sorted array to a BST
The middle element becomes the root; recurse on both halves to keep the tree shallow.
Balance a binary search tree
Read the tree in order, then rebuild it from the middle outward.
AVL tree insertion
Insert like a BST, then repair the first unbalanced node on the way back with one or two rotations.
Identify the required AVL rotation
Classify the imbalance as left-left, left-right, right-left or right-right and name its fix.
AVL tree deletion
Delete, then rebalance on the climb home: one removal can unbalance several ancestors.
Validate red-black tree properties
Check both invariants: no red node has a red child, and every root-to-leaf path carries the same black height.
Red-black tree insertion
Insert red, then recolor and rotate through the standard cases until the colour rules hold again.
Red-black tree deletion
The hardest repair: the double-black case, handled with recolouring and rotations.
Heap
20 concepts · 19 playableThe tree and its array shadow, sifting in sync.
Insert / extract (sift up / sift down)
Build a min heap
Kth largest element in an array
Find median from a data stream
Find minimum in a min heap
The smallest value is always the root, so the answer is one cell away.
Validate a binary min heap
Every parent must be at most its children, in the tree shape or in the array that stores it.
Find parent and children in a heap array
Use the index arithmetic: children of i live at 2i+1 and 2i+2, the parent at (i-1)/2.
Insert into a min heap
Append at the next free cell, then sift up while the new value beats its parent.
Delete minimum from a min heap
Move the last cell into the root, then sift down while a child is smaller.
Implement sift down
The repair walk for removals and heap building, choosing the smaller child at every step.
Top K frequent elements
Count with a map, then keep the best K counts in a heap (or bucket them).
K closest points to origin
Keep a K-sized max-heap of the closest points seen so far.
Kth largest element in a stream
Maintain a K-sized min-heap: its root is the kth largest at every moment.
Merge K sorted arrays
Load the front of each array into a min-heap and always take the smallest next value.
Smallest range covering elements from K lists
Slide a window over the merged order: the heap gives the current minimum, a running maximum closes the range.
Find K pairs with smallest sums
Grow candidates through a heap: push the next pair from each list as the current one is taken.
Meeting rooms II
Sort starts and keep a min-heap of end times; a room frees when its end passes.
Task scheduler
Count task kinds, then lay them out in cooling slots: the most frequent kind sets the frame.
Single-threaded CPU
Sort tasks by arrival, keep a heap of available tasks by duration, and jump the clock when idle.
Process tasks using servers
Two heaps: free servers by weight and busy servers by finish time, with a tie-break rule for equal weights.
Graph
46 concepts · 43 playableFrontiers, distances and spanning trees — the richest canvas.
BFS traversal of a graph
DFS traversal of a graph
Dijkstra's shortest path
Topological sort
Cycle & bipartite detection
MST: Prim / Kruskal + DSU
Bellman-Ford: detect a negative cycle
Floyd-Warshall: all-pairs shortest paths
Grid BFS (islands, rotten oranges)
Count vertices and edges
Read the edge list and tally the distinct vertices and the number of links.
Find the degree of each vertex
One pass over the edges adds one to each endpoint (both directions when edges are undirected).
Identify directed vs undirected graph properties
Decide from the statement and the data whether links have a direction, and what that changes.
Build an adjacency list
From an edge list, give every vertex the list of its neighbours.
Convert an adjacency matrix to an adjacency list
One row at a time: a set cell becomes a neighbour entry.
Convert an edge list to an adjacency list
Append both endpoints to each other's lists in a single pass.
Find whether a path exists
Expand in rings from the source until the target appears or the frontier dries up.
Shortest path in an unweighted graph
BFS levels are distances: the first time a vertex is reached is by the fewest edges.
Rotting oranges
Multi-source BFS: start from every rotten cell, advance one level per minute, count what never rots.
Word ladder
Words are vertices and one-letter changes are edges; BFS finds the shortest chain.
Find connected components
One DFS per unvisited vertex; each launch discovers exactly one component.
Number of islands
Grid-as-graph flood fill: each unvisited land cell starts one island walk.
Clone graph
DFS or BFS with a map from original node to its copy, so shared neighbours are copied once.
Detect cycle in an undirected graph
Track parents as you dive; an already-visited neighbour that is not the parent closes a cycle.
Is graph bipartite?
Paint the graph with two colours; an edge that meets its own colour means the answer is no.
Possible bipartition
People are vertices and dislikes are edges: two groups exist exactly when the graph is bipartite.
Two-color a graph
The colouring walk itself, tracked with a colour array and a queue or stack.
Course schedule
Prerequisites are directed edges; a completion order exists exactly when there is no cycle.
Course schedule II
Produce an actual order: Kahn's queue drains zero-indegree courses, or DFS records finishing times and reverses.
Alien dictionary
Compare neighbouring words to learn letter order, topologically sort the letters, and watch the prefix trap.
Network delay time
Single-source Dijkstra: the answer is the largest shortest distance, or impossible if some node never arrives.
Cheapest flights within K stops
The stop limit breaks plain Dijkstra: level-limited BFS over states, or Bellman-Ford run k+1 rounds.
Minimum cost to connect all points
Points are vertices and distances are weighted edges; either MST algorithm builds the cheapest network.
Kruskal's minimum spanning tree
Sort edges by weight and take each one that joins two different groups, tracked with union-find.
Prim's minimum spanning tree
Grow one tree: always add the cheapest edge that leaves the current set, via a priority queue.
Connecting cities with minimum cost
An MST in disguise with a catch: pick the cheapest links so every city is connected, or report -1.
Implement disjoint set union
Two arrays and two tricks: find with path compression, union by size or rank.
Number of provinces
Each connected group is a province; union the pairs and count the remaining roots.
Redundant connection
The first edge whose endpoints are already united is the one that closes the cycle.
Accounts merge
Emails are the vertices and accounts are unions of them; group the email sets under one name.
Number of islands II
Grow the map cell by cell, unioning with live neighbours and tracking the island count as cells land.
Find bridges in a graph
DFS with discovery times and low values: an edge is a bridge when its child cannot reach back past it.
Find articulation points
The vertex version of the same walk, with the root handled by its child count.
Critical connections in a network
The same bridges, asked as a whole list: report every connection whose failure splits the network.
Find strongly connected components
Groups where everyone reaches everyone, found by one of the two classic pass orderings.
Kosaraju's algorithm
One DFS records finishing times, the reversed graph's DFS in that order reveals the components.
Tarjan's strongly connected components
A single DFS with low-link values pops a component each time a cycle root closes.
Greedy
28 concepts · 28 playableMake a local decision that can be proven safe for the global solution.
Activity selection / meeting rooms
Fractional knapsack
Huffman coding
Jump game
Assign cookies
Give each child at most one cookie so the most children are satisfied.
Lemonade change
Sell lemonade at 5 per cup and give exact change from the bills collected so far.
Boats to save people
Carry everyone in boats that take two people, using as few boats as the weight limit allows.
Candy
Hand out candy by rating, one rule for each direction, using as few pieces as possible.
Non-overlapping intervals
Remove the fewest intervals so the remaining ones never overlap.
Gas station
Minimum number of arrows to burst balloons
Burst every balloon with the fewest vertical arrows, each shot at one x position.
Minimum taps to water a garden
Water the whole garden with the fewest taps, where each tap reaches a range.
Can attend all meetings
Decide whether a person can attend every meeting without any overlap.
Minimum platforms
Count the platforms a station needs so no train ever waits.
Car pooling
Check whether a car of fixed capacity can serve every trip without ever overfilling.
Employee free time
Find the stretches of time when every employee is free.
Job sequencing with deadlines
Schedule unit-time jobs by deadline and profit to earn the most before the deadlines pass.
Course schedule III
Take the most courses so the total duration stays inside each course's last day.
Maximum number of events that can be attended
Attend the most events, at most one per day, when each event runs for one day inside a range.
Minimum difficulty of a job schedule
Split jobs across d days, in order, to keep the sum of each day's hardest job as small as possible.
Pick the largest available reward
Practice the heap pattern on a simple stream: keep candidates available and always take the current best.
IPO
Start at most k projects you can afford, choosing each to grow capital as fast as possible.
Reorganize string
Rearrange letters so no two neighbours are the same.
Minimum cost to hire k workers
Hire exactly k workers so that wages keep their quality ratios fair and the bill stays minimal.
Prove the earliest-finish interval choice
Write the exchange argument that the earliest-finishing interval is always safe to take first.
Reconstruct the greedy proof for activity selection
Rebuild the swap proof for activity selection from scratch, one step at a time.
Prove Kruskal's safe edge choice
Show that the smallest edge creating no cycle can always belong to a minimum spanning tree.
Design and prove a greedy rule
Invent a greedy rule for a custom scheduling problem and prove it safe before coding it.
Dynamic Programming
49 concepts · 48 playableBreak a problem into overlapping states, define what each state means, and reuse answers instead of recomputing them.
Edit Distance
Find the minimum number of operations to convert word1 to word2.
Longest Palindromic Substring
A palindrome reads the same both ways. Watch the DP table fill smallest-window-first for "babad": do the edges match, and was the inside already a palindrome?
Longest Palindromic Subsequence
Longest Common Subsequence
0/1 Knapsack
Choose each item at most once to maximize total value without exceeding the weight capacity.
Subset sum
Decide whether some of the values reach an exact target sum, with each value used at most once.
Coin change
Make an amount with the fewest coins, when each coin value may be used as many times as you like.
Climbing stairs / house robber
Longest increasing subsequence
Find the length of the longest strictly increasing subsequence of a row of numbers.
Stock suite (cooldown, k transactions)
Palindrome partitioning / MCM
Wildcard matching
Fibonacci number
Compute the nth Fibonacci number with a table instead of a branching recursion.
Minimum cost climbing stairs
Climb one or two steps at a time, paying each visited step's cost, for the cheapest way up.
Decode ways
Count how many ways a digit string can be read as letters from 1 to 26.
Russian doll envelopes
Nest the most envelopes without rotating them; both dimensions must be strictly smaller.
Maximum profit in job scheduling
Choose non-overlapping jobs so the total pay is as large as possible.
Unique paths
Count the ways across a grid moving only right or down.
Unique paths II
Count grid paths when some cells are blocked.
Minimum path sum
Find the cheapest right or down path through a grid of costs.
Triangle
Find the smallest top-to-bottom path through a triangle of numbers.
Dungeon game
Find the least starting health that survives a dungeon of damage and healing.
Cherry pickup
Send two walks through a grid to collect the most cherries.
Partition equal subset sum
Split a set into two parts with equal sums, when possible.
Target sum
Count the ways to assign plus and minus signs so the expression hits a target.
Coin change II
Count the combinations of coins that make an amount.
Ones and zeroes
Pick the largest subset of strings that fits the given limits of zeroes and ones.
Profitable schemes
Count the groups of schemes that reach a profit with a bounded number of members.
Distinct subsequences
Count how many ways the first string contains the second as a subsequence.
Interleaving string
Decide whether a third string interleaves the other two without reordering them.
Word break
Decide whether a string splits into dictionary words.
Regular expression matching
Match a string against a pattern with dot and star.
Best time to buy and sell stock
Pick one buy day and one later sell day for the best profit.
Best time to buy and sell stock II
Trade any number of times for the best total profit.
Best time to buy and sell stock with cooldown
Trade with a one-day cooldown after every sale.
Best time to buy and sell stock with transaction fee
Trade any number of times while paying a fee on every transaction.
Minimum cost to combine intervals
Combine small intervals at a cost per merge and pay as little as possible.
Burst balloons
Burst every balloon for maximum coins, where popping rewards its neighbours.
Minimum cost to cut a stick
Cut a stick at the given positions for the cheapest possible total.
Strange printer
Print a string with a printer that may reuse the same character in one turn.
Subtree sum
Return the sum of every value in a subtree.
Sum of distances in tree
Report the total distance from every node to all other nodes.
Encode used items as a bitmask
Practice packing a used-set into an integer and reading it back.
Minimum cost assignment
Assign workers to jobs one-to-one at the lowest total cost.
Can I win
Decide whether the first player can force reaching a total first.
Partition to K equal sum subsets
Split a set into k parts of equal sum.
Traveling salesman problem
Visit every city once and return for the cheapest tour.
Shortest path visiting all nodes
Walk a graph visiting every node in the fewest steps.
Minimum XOR sum of two arrays
Pair two arrays to minimize the sum of XORs.
Number Theory
46 concepts · 46 playableNumbers as mathematical structure: divisibility, primes, factors, modular arithmetic, and counting.
Sieve of Eratosthenes
GCD / LCM (Euclid)
Modular exponentiation
Pascal's triangle
Build Pascal's triangle row by row, one addition per inner entry.
Check if one number divides another
Decide whether one number divides another exactly.
GCD of an array
Fold Euclid across a list to find the GCD of every value.
Greatest common divisor of strings
Find the largest string that repeats to build both inputs.
Count common divisors
Count the numbers that divide both given values.
Minimum operations using GCD structure
Reshape values into each other with the fewest gcd-sized steps.
Check prime
Test one number for primality up to its square root.
Count primes
Count the primes below a limit with a sieve.
Closest prime numbers in range
Find the closest prime pair inside a range.
Prime subtraction operation
Make an array strictly increasing by subtracting primes.
Segmented sieve for a large range
Sieve the primes inside a huge interval far from 1.
Prime factorization of a number
Write a number as a product of primes with exponents.
Count prime factors
Count prime factors with and without multiplicity.
Count divisors
Multiply (exponent + 1) over the prime factorization.
Sum of divisors
Multiply small power sums, one per prime, for the divisor sum.
Distinct prime factors of product of array
Union the prime factor sets of an array and count.
Smallest prime factor preprocessing queries
Precompute smallest prime factors, then factor many queries fast.
Normalize a number modulo m
Bring any integer into the 0 to m − 1 range.
Modular addition and multiplication
Evaluate sums and products under a modulus without overflow.
Product of array except self modulo m
Multiply everything except one value, under a modulus.
Modular prefix products
Answer range product queries modulo m.
Large arithmetic expression modulo m
Evaluate a big expression with reductions at every step.
Power of a number
Compute x^n with repeated multiplication or squaring.
Pow(x, n)
Compute x^n where n can be negative.
Super pow
Compute a^b where the exponent arrives as a digit array.
Count good numbers
Count digit strings by per-position choices with modular exponentiation.
Huge exponent modulo m
Evaluate a power whose exponent is too large to iterate.
Verify Bezout coefficients
Check whether given coefficients satisfy a×x + b×y = gcd(a, b).
Extended GCD
Return the GCD with Bezout coefficients x and y.
Solve linear Diophantine equation
Find one integer solution of a×x + b×y = c.
Count integer solutions to ax + by = c
Step through the solution family and count the ones inside bounds.
Find modular inverse by brute force for small m
Scan multiples until one reduces to 1.
Modular inverse using extended Euclid
Read the inverse off the coefficient the extended algorithm returns.
Modular division
Divide under a modulus by multiplying with an inverse.
Compute nCr mod prime
One combination under a prime modulus.
Inverse factorials for many combination queries
Precompute inverse factorials for constant-time nCr lookups.
Compute nCr for small values
Combination counts by formula or Pascal's rule.
Compute nPr
Count ordered selections with the falling chain.
Count ways to choose teams
Count team formations, labelled or not.
Many nCr queries modulo prime
One precompute, then three multiplications per query.
Find a small number matching two remainders
Meet two remainder tracks at one value.
Chinese Remainder Theorem for pairwise-coprime moduli
Build the combined answer term by term with inverses.
Generalized CRT with non-coprime moduli
Merge conditions pairwise and detect contradictions.
Trie
22 concepts · 22 playableShared prefixes become shared paths, turning strings into a searchable tree.
Implement trie (insert / search / startsWith)
Autocomplete / search suggestions
Build a trie from a small word list
Turn a handful of words into shared prefix paths by hand or in code.
Count nodes in a trie
Count one node per distinct prefix character, shared paths once.
Identify shared prefix paths
Spot which prefixes several words share before writing code.
Compress a trie into shared prefix groups
Fold branchless chains into single labels to compress a dictionary.
Design add and search words data structure
Support word search where a dot matches any single letter.
Implement trie delete
Unmark a word, then prune only the nodes nothing else needs.
Design a memory-efficient trie
Drop the fixed 26-slot array for a compact child structure.
Count words with a given prefix
Walk to the prefix node, then count flagged words below it.
Longest common prefix
Walk while each node has one child and is not a word end.
Map sum pairs
Sum the values of keys sharing a prefix, with values updating.
Ranked autocomplete with frequency updates
Return top suggestions while frequencies keep changing.
Replace words
Replace each word by the shortest dictionary root that prefixes it.
Find shortest dictionary prefix
Stop at the first flagged node on the walk of one word.
Word search with a small dictionary
Grid search guided by the trie, pruning at the first missing child.
Stream of characters
Detect dictionary words ending at the newest stream position.
Insert binary numbers into a bitwise trie
One level per bit from the top down, creating missing children.
Find best opposite-bit path for a small query
Prefer the opposite child at every level and read off the XOR.
Max XOR pair (bitwise trie)
Count pairs with XOR in a given range
Count pairs below each bound with subtree sizes, then subtract.
Maximum genetic difference query
Answer ancestor XOR queries with a trie that follows the DFS.
String Matching
35 concepts · 35 playableFind a pattern inside text by reusing information about what has already matched.
KMP + LPS array
Rabin–Karp rolling hash
Z-algorithm
Find first pattern occurrence
Report the first index where the pattern occurs, or minus one.
Count pattern occurrences
Count complete matches across the text, overlaps included.
Find all match positions
List every starting index where the pattern occurs.
Find overlapping matches
Catch matches that share characters, like aa inside aaaa.
Compare multiple matching strategies
Run the naive scan, a rolling hash and the pattern's border table over one text, then compare what each one spent.
Implement naive pattern matching
Try every start and compare characters until a mismatch.
Count overlapping pattern matches
Continue at the next start after every match, never skipping.
Compare naive search on different inputs
Measure how the input's shape changes the comparison count.
Construct a worst-case input for naive matching
Build the repeated-run shape that forces the quadratic cost.
Compute prefix hashes
Build the fingerprint and power arrays in one forward pass.
Compare equal-length substrings
Two prefix reads make each substring a comparable fingerprint.
Longest repeated substring
Find the longest substring that appears at least twice.
Detect duplicate substrings
Hash fixed-length windows into a set and watch for repeats.
Substring equality queries
Answer many equality questions with prefix fingerprints.
Compare fixed-length windows
Roll one fingerprint forward instead of rehashing each window.
Repeated DNA sequences
Find the ten-letter sequences that appear more than once.
Find all anagrams with hashing
Slide window fingerprints of the pattern's length.
Longest duplicate substring
Binary search the length and test window fingerprints.
Find pattern with KMP
Scan once with LPS fallbacks and no backward text movement.
Find pattern with Z
Z values equal to the pattern length mark the matches.
Repeated substring pattern
Decide whether a string repeats a shorter block.
Longest happy prefix
The last LPS entry is the longest proper prefix that is also a suffix.
Shortest palindrome
Prepend the fewest characters to make a palindrome, via KMP matching.
String period queries
Answer period questions from borders in the LPS array.
Expand around center
Find palindromes by expanding from odd and even centers.
Count palindromic substrings
Count every palindromic substring in one linear pass.
Longest palindrome queries with preprocessing
Answer in-range palindrome questions from precomputed radii.
Palindrome pairs with advanced matching
Pair strings whose concatenation reads as a palindrome.
Simulate failure fallback on small patterns
Walk the fallback chain by hand until an edge exists.
Count dictionary pattern occurrences
One automaton pass, then tally each pattern's matches.
Aho-Corasick pattern search
Search one text for many patterns with trie plus failure links.
Dynamic multi-pattern matching
Keep multi-pattern matching working while patterns come and go.
Range Queries
40 concepts · 40 playableTurn repeated range questions into efficient queries by trading preprocessing and memory for faster operations.
Segment tree build / query / update
Lazy propagation
Fenwick tree
Answer range sum by scanning
Add the cells of each range directly and know when that is enough.
Identify static vs dynamic query problems
Classify statements by whether updates exist before solving.
Choose the right range query structure
Match a statement's operations to the matching structure.
Compare query costs
Measure build, query and update work across the candidate structures.
Design a data structure from query and update requirements
Assemble a structure from a list of operations and constraints.
Range sum query - immutable
Many range sums on a fixed array: prefix sums, two reads per query.
Corporate flight bookings
Apply many booking ranges and read the per-flight totals.
Range addition
Apply many range additions to a zero array, then read the values.
Multiple range updates and queries offline
Mix many range updates with range queries when everything is known in advance.
Rank transform of an array
Replace values by ranks among their sorted distinct peers.
Range frequency with compressed values
Count how often a set of values appears across ranges.
Build sparse table levels
Fill the power-of-two levels of the table, one combination per cell.
Range minimum query
Static range minima from two overlapping power-of-two blocks.
Range GCD query
The same two-block trick on an idempotent operation.
Many static RMQ queries
Constant time per minimum query at scale, memory included.
Range sum with blocks
Edge scans plus whole-block sums answer each range.
Point update in block decomposition
Change one cell and adjust exactly one block summary.
Range minimum with sqrt decomposition
Block minima plus edge scans, refreshed on updates.
Frequency queries with block decomposition
Per-block frequency tables for range counting.
Fenwick prefix sum
Walk left subtracting the lowbit until zero.
Fenwick point update
Walk right adding the lowbit through the covering ranges.
Range sum query - mutable
Range sums under point updates with a Fenwick tree or segment tree.
Count smaller numbers after self
Sweep from the right with a compressed Fenwick tree of seen values.
Reverse pairs with compression
Count pairs where the earlier value exceeds twice the later one.
Order statistics with Fenwick tree
Rank and select queries under insertions, by binary lifting on the tree.
Build a segment tree
Leaves first, then combine upward; verify the stored summaries.
Static range sum with segment tree
The three overlap cases on a tree that never changes.
Dynamic range maximum with custom merge state
Store a custom state per node and merge it under updates.
Simulate one lazy range update
Walk an update through the tree and park its markers.
Range addition and range sum
Lazy add markers with summaries scaled by segment length.
Range assignment and range sum
Assignment markers overwrite; compose marker kinds in order.
Multiple lazy operations with composition
Define how every pair of markers composes and push consistently.
Simulate moving range window
Stretch and shrink the window by hand, adjusting the answer per step.
Distinct values in range
Mo's algorithm with a frequency table; the count moves at zero and one.
Frequency of a value in many ranges
Per-value frequencies maintained as the window moves.
Powerful array
Running sums of frequency squared times value under window moves.
Mo's algorithm with modifications
Three pointers over left, right and time with alternating orderings.
Custom / Puzzle
1 concept · 1 playableOne-off canvases when no format fits.