PrepStack Free

Pattern catalog

Search by title, family, or template ID. Free entries open fully; every other entry shows the Pro boundary.

Pro only = requires SSO

DFS Components and Reachability

Traversal and connectivity · dfs-components

Follow adjacency as deeply as needed to decide reachability, enumerate components, or aggregate each component. The goal is to exhaust a region, not to minimize travel distance.

Freefirst family
BFS Connectivity Traversal

Traversal and connectivity · bfs-components

Use a FIFO queue to exhaust reachable regions without recursion risk, while leaving room to record levels, parents, or component labels.

Freefirst family
Grid Flood Fill

Traversal and connectivity · grid-flood-fill

Treat a matrix as an implicit graph and consume the maximal region connected to a seed, supporting recoloring, area, boundary-touch, and enclosure analysis.

Freefirst family
Topological Sort / Indegree Elimination

Traversal and connectivity · topological-sort

Turn prerequisites into an executable order by repeatedly removing tasks with no unfinished predecessors; detect directed cycles and support execution layers or DAG DP.

Freefirst family
Unweighted Shortest-Path BFS

Ordered frontier and path · bfs-unweighted-shortest

Every action counts exactly once and has identical cost.

Pro onlyComplete Pro library
0-1 BFS

Ordered frontier and path · zero-one-bfs

Actions split into free and one-charge transitions.

Pro onlyComplete Pro library
Minimax / Bottleneck Dijkstra

Ordered frontier and path · minimax-dijkstra

The objective says minimize the maximum, minimum required threshold, or bottleneck.

Pro onlyComplete Pro library
Binary Search on a Sorted Domain

Binary search and monotone answer · binary-search-sorted

Exploit sorted order so each comparison safely discards half the candidates, locating an exact target or proving absence.

Freeused by LC 1–100
Binary-Search Boundary / First True

Binary search and monotone answer · binary-search-boundary

Locate the first True in a monotone sequence F…F T…T, and derive last-false, lower-bound, or upper-bound variants through predicate design.

Freeused by LC 1–100
Binary Search on the Answer

Binary search and monotone answer · binary-search-answer

Avoid constructing the optimum directly; ask can(x) over candidate answers and exploit monotone feasibility to find a minimum feasible or maximum feasible value.

Freeused by LC 1–100
Opposite-Direction Two Pointers

Pointers and sliding window · two-pointers-opposite

Move pointers inward from both ends, using order or endpoint dominance to eliminate at least one endpoint safely on every step.

Freeused by LC 1–100
Same-Direction / Read-Write Pointers

Pointers and sliding window · two-pointers-same-direction

Use read to scan input and write to maintain a normalized output prefix, performing stable filtering, deduplication, compaction, or merging in place.

Freeused by LC 1–100
Fixed-Size Sliding Window

Pointers and sliding window · sliding-window-fixed

Evaluate every contiguous segment of exactly k items by adding one entrant and removing one leaver, reducing repeated O(k) work to O(n) total.

Freeused by LC 1–100
Variable-Size Sliding Window

Pointers and sliding window · sliding-window-variable

Expand a contiguous interval on the right and move the left edge only forward, maintaining constraints incrementally to find a longest valid or shortest covering window.

Freeused by LC 1–100
Linked-List Pointer Rewiring

Pointers and sliding window · linked-list-rewire

Save successors, rewrite next, and advance role pointers to reverse, delete, splice, segment, or reorder a linked list in O(1) auxiliary space.

Freeused by LC 1–100
Prefix Sum / Range Aggregation

Prefix, difference, and hashed state · prefix-sum

Many contiguous range sums are queried on one static array.

Pro onlyComplete Pro library
Prefix State plus Hash Frequency

Prefix, difference, and hashed state · prefix-state-hash

Rewrite a contiguous-interval condition as a relationship between the current prefix and a historical prefix, using a hash table to avoid O(n²) interval enumeration.

Freeused by LC 1–100
Difference Array / Batched Range Updates

Prefix, difference, and hashed state · difference-array

There are many range additions or subtractions and results are read only after all updates.

Pro onlyComplete Pro library
Frequency Table / Coordinate Counting

Prefix, difference, and hashed state · frequency-counting

Map items into a key domain and retain occurrence counts, representing a multiset rather than positions for equality, pairing, buckets, voting, and frequency-driven reconstruction.

Freeused by LC 1–100
Stack-Based State Simulation

Stack and monotone deque · stack-state-machine

Use a LIFO stack to preserve unfinished contexts or undoable history, making nested parsing, expression reduction, path normalization, and recursive execution explicit.

Freeused by LC 1–100
Balanced-Delimiter Stack

Stack and monotone deque · balanced-delimiter-stack

Validate or analyze nested delimiter types so each closer matches the most recent unmatched opener of the corresponding kind, optionally tracking positions, depth, or longest valid spans.

Freeused by LC 1–100
Monotonic Stack for Nearest Greater/Smaller

Stack and monotone deque · monotonic-stack

Keep unresolved candidate indexes monotone by value so each new item resolves every dominated candidate once, supporting nearest boundaries, spans, rectangles, and contribution counting.

Freeused by LC 1–100
Top-K bounded heap

Heap, selection, and stream · top-k-heap

Only a kth value or the best k items are needed; the remaining order is irrelevant.

Pro onlyComplete Pro library
K-way merge heap

Heap, selection, and stream · k-way-merge-heap

Merge several internally ordered sources into one ordered stream, or consume only its global prefix. Each source exposes one unconsumed head; a heap chooses the smallest head.

Freeused by LC 1–100
Two heaps for streaming median

Heap, selection, and stream · two-heaps-stream

Values arrive one by one and the median is queried after insertions.

Pro onlyComplete Pro library
Interval sorting greedy

Greedy and scheduling · interval-sort-greedy

Turn interval choices into an irreversible coordinate scan. Sorting by a start or finish endpoint exposes a boundary that supports maximum compatibility, minimum conflict deletion, merging, or coverage.

Freeused by LC 1–100
Exchange-argument greedy ordering

Greedy and scheduling · exchange-order-greedy

Derive and prove a local order: whenever adjacent decisions violate it, swapping them cannot worsen the objective. Repeating those swaps transforms an optimum into the greedy order. This is a proof discipline, not permission to sort by intuition.

Freeused by LC 1–100
Divide, recurse, and combine

Divide and conquer · divide-and-conquer

Split a size-n problem into structurally identical, nearly independent subproblems, solve them recursively, and recover cross-boundary information in a controlled combine step. The design center is the returned summary, not the presence of two recursive calls.

Freeused by LC 1–100
Merge-sort cross-half counting

Divide and conquer · merge-sort-counting

Use sorted halves during merge-sort combination to replace pair-by-pair cross-midpoint checks with monotone-pointer batch counting.

Freeused by LC 1–100
Quickselect order statistic

Divide and conquer · quickselect

Only a kth smallest/largest, median, or rank boundary is needed.

Pro onlyComplete Pro library
Linear dynamic programming

Dynamic programming · linear-dp

Process a sequence by prefixes and collapse an exponential decision tree into a small family of states at position i. Each step depends only on already finalized earlier positions.

Freeused by LC 1–100
Grid dynamic programming

Dynamic programming · grid-dp

On a grid whose movement directions form a DAG, combine finalized neighboring states into the optimum or count for each cell instead of enumerating all paths.

Freeused by LC 1–100
0/1 or unbounded knapsack DP

Dynamic programming · knapsack-dp

Each object has a weight/cost and possibly a value.

Pro onlyComplete Pro library
Subsequence dynamic programming

Dynamic programming · subsequence-dp

For selections that may skip elements while preserving relative order, use a state ending at a position or relating two prefixes to compute longest, matching, or edit objectives.

Freeused by LC 1–100
Interval dynamic programming

Dynamic programming · interval-dp

A subproblem is uniquely described by contiguous endpoints l and r.

Pro onlyComplete Pro library
Finite-state-machine DP

Dynamic programming · state-machine-dp

At each time, the process occupies one of a few mutually exclusive modes.

Pro onlyComplete Pro library
Tree dynamic programming

Dynamic programming · tree-dp

Exploit a tree's acyclic hierarchy by returning a small set of boundary states from each node to its parent. Independent child subtrees then combine into selection, path, covering, or counting answers.

Freeused by LC 1–100
Subset / combination backtracking

Backtracking and constraint search · subsets-combinations-backtracking

Enumerate set selections systematically. A start index gives every combination one canonical generation order, while a mutable path is extended and undone around each recursive call.

Freeused by LC 1–100
Permutation backtracking

Backtracking and constraint search · permutation-backtracking

Construct an ordered arrangement one position at a time. A used set or in-place prefix records occupied elements, while same-level duplicate pruning avoids equivalent branches.

Freeused by LC 1–100
Constraint-satisfaction backtracking

Backtracking and constraint search · constraint-backtracking

Find one or all assignments satisfying constraints. Assign one variable at a time, maintain local conflict summaries immediately, and undo on failure; variable/value ordering and propagation make contradictions appear early.

Freeused by LC 1–100
Tree recursive aggregation

Tree, BST, and trie · tree-recursive-aggregation

Use postorder so each node receives child summaries before returning only the minimal information its parent needs. At the same node, update complete global candidates that cannot be extended upward as a whole.

Freeused by LC 1–100
Tree level-order BFS

Tree, BST, and trie · tree-level-order

Expand a tree by depth with a FIFO queue. Freeze the queue length each round to process exactly one layer, enabling per-level summaries, views, and shallowest-match queries.

Freeused by LC 1–100
BST ordering / inorder traversal

Tree, BST, and trie · bst-order-invariant

Exploit the BST's global order: inorder traversal is sorted, and every node inherits a value range jointly imposed by all ancestors. This supports validation, search, rank, and predecessor/successor queries.

Freeused by LC 1–100
Trie prefix search

Tree, BST, and trie · trie-prefix-search

Materialize shared string prefixes as shared paths so insertion, full-word lookup, prefix lookup, and prefix-guided DFS pruning advance only by character depth.

Freeused by LC 1–100
Union-Find dynamic connectivity

DSU, MST, and offline activation · union-find-connectivity

Repeated merge-group and same-group operations

Pro onlyComplete Pro library
Kruskal minimum spanning tree

DSU, MST, and offline activation · kruskal-mst

Connect every vertex at minimum total construction cost

Pro onlyComplete Pro library
Offline activation with DSU

DSU, MST, and offline activation · offline-activation-dsu

Many connectivity queries at different thresholds

Pro onlyComplete Pro library
Fenwick tree

Range-query data structures · fenwick-tree

Point updates and range queries interleave online

Pro onlyComplete Pro library
Sparse table static RMQ

Range-query data structures · sparse-table

The array never changes after construction

Pro onlyComplete Pro library
KMP / prefix-function matching

String matching, hashing, and palindrome · kmp-string-matching

Find every exact occurrence of one pattern in linear time by reusing matched prefixes instead of retreating the text pointer.

Freeused by LC 1–100
Rolling hash / Rabin-Karp

String matching, hashing, and palindrome · rolling-hash

Many substring-equality checks

Pro onlyComplete Pro library
Center expansion / Manacher palindrome

String matching, hashing, and palindrome · palindrome-center

Assign every palindromic substring to a unique center and expand symmetrically to count or maximize it; upgrade to Manacher at larger scale.

Freeused by LC 1–100
GCD / LCM and divisibility

Math, number theory, and combinatorics · gcd-number-theory

A largest common unit is requested

Pro onlyComplete Pro library
Sieve and prime factorization

Math, number theory, and combinatorics · sieve-prime-factorization

All primes in a bounded range are needed

Pro onlyComplete Pro library
Modular arithmetic and fast power

Math, number theory, and combinatorics · modular-arithmetic

Preserve congruence classes in large counts and powers, using repeated squaring to reduce exponentiation to logarithmic time.

Freeused by LC 1–100
Combinatorial counting / inclusion-exclusion

Math, number theory, and combinatorics · combinatorics-counting

Map a huge enumeration space to a countable structure and compute its size with product rules, binomial coefficients, or inclusion-exclusion.

Freeused by LC 1–100
Bitwise invariants / XOR cancellation

Bit manipulation and bitmask state · bitwise-invariants

Reason independently per bit and use XOR cancellation, bit counts, or masks to compress parity and uniqueness information.

Freeused by LC 1–100
Bitmask subset enumeration

Bit manipulation and bitmask state · bitmask-enumeration

n is small and every subset matters

Pro onlyComplete Pro library
Bitmask dynamic programming

Bit manipulation and bitmask state · bitmask-dp

When the chosen set determines the future, use its mask as a DP state and reuse the best subproblem across orderings.

Freeused by LC 1–100
Sweep line with sorted events

Geometry, sweep, simulation, and parsing · line-sweep-events

Interval overlap or peak concurrency

Pro onlyComplete Pro library
Explicit simulation / state machine

Geometry, sweep, simulation, and parsing · simulation-state-machine

Translate process rules into minimal sufficient state and a pure transition, replaying behavior exactly and detecting cycles when useful.

Freeused by LC 1–100
Parsing / token state machine

Geometry, sweep, simulation, and parsing · parsing-tokenization

Use a scan pointer and finite modes to cut a raw character stream into typed tokens for expressions, paths, or structured text.

Freeused by LC 1–100