Pattern-Based Learning

Master DSA by Pattern

Learn the skeleton once, apply to hundreds of problems. Each pattern breaks down into variations - the template stays 90% the same, only the details change.

Part I - Arrays & Pointers
ij

Two Pointers

Opposite-direction, fast-slow, sliding compare.

610problems
4 vars
ij

Sliding Window

Turn O(n²) subarray loops into O(n) with a moving window.

610problems
5 vars
ij

Binary Search

Narrow the search space in half each step - the O(log n) hammer.

3,709problems
5 vars
ij

Prefix Sum

Precompute running sums for O(1) range queries and subarray counting.

4,313problems
Learn →
ij

Two Sum Family

HashMap-based pair/triple sum lookups. Two Sum, Three Sum, Four Sum, best time to buy/sell.

4,313problems
Learn →
ij

Array Tricks

Cyclic rotation, reversal-based operations, in-place swaps, and the Dutch flag.

4,313problems
Learn →
ij

Difference Array

O(1) range updates with O(n) reconstruction. Range increment/decrement queries.

4,313problems
Learn →
ij

Contribution Technique

Count how many subarrays each element participates in.

4,313problems
Learn →
ij

Binary Search on Answer

When the answer space is monotonic, binary search the answer and check feasibility.

4,313problems
Learn →
ij

Permutation Patterns

Next permutation, permutation ranking, generating permutations systematically.

4,313problems
Learn →
ij

Word Break Variants

Segment strings using dictionary words, with DP and memoization.

4,313problems
Learn →
ij

Shortest Common Supersequence

Shortest string that has two given strings as subsequences.

4,313problems
Learn →
ij

Kadane's Algorithm Variants

Maximum subarray sum in O(n), with circular, 2D, and product variants.

4,313problems
Learn →
ij

Two Pointers - Advanced

Multiple pointers, three-way partition, k-sum beyond three.

4,313problems
Learn →
ij

Cyclic Sort

Place each number at its correct index in O(n). For problems with numbers 1..n.

4,313problems
Learn →
Part II - Linked Structures
ij

Linked List

Reverse, merge, detect cycles, find middle, LRU cache.

1,135problems
Learn →
ij

Trees

Binary trees, BSTs, traversals (in/pre/post/level), LCA, diameter.

2,714problems
Learn →
ij

Advanced Trees

Fenwick tree, segment tree, sqrt decomposition, Mo's algorithm, treap.

924problems
Learn →
ij

Sparse Table

O(1) range min/max/gcd queries with O(n log n) preprocessing.

924problems
Learn →
ij

Segment Tree with Lazy Propagation

Range updates and range queries in O(log n). Lazy tags for assignment/additive updates.

924problems
Learn →
ij

Cycle Detection

Floyd's tortoise and hare, Brent's algorithm. Cycle in LL, arrays, functional graphs.

1,135problems
Learn →
ij

Tree Construction

Build trees from traversals, serialization, construct BST from preorder.

2,714problems
Learn →
ij

Lowest Common Ancestor

Binary lifting, Euler tour + RMQ, tarjan's offline LCA.

1,290problems
Learn →
ij

DSU on Tree (Sack)

Small-to-large merging on trees for offline subtree queries in O(n log n).

1,290problems
Learn →
ij

Tree Diameter

Two BFS/DFS technique. Find longest path in any tree. Center(s) of tree.

1,290problems
Learn →
ij

Offline LCA

Tarjan's offline algorithm for batch LCA queries using DSU.

1,290problems
Learn →
ij

Tree Isomorphism

AHU algorithm, rooted/unrooted tree isomorphism, canonical form.

1,290problems
Learn →
ij

Persistent Union-Find

Union-find with rollback capability for offline queries.

1,290problems
Learn →
ij

Binary Lifting

Jump pointers for ancestors, LCA, path queries in O(log n).

2,714problems
Learn →
ij

Segment Tree Basics

Point updates, range queries, building and querying segment trees.

2,714problems
Learn →
ij

Tree Path Problems

Path sum queries, max/min edge on path, path aggregates with binary lifting.

2,714problems
Learn →
ij

Iterative Tree Traversal

Morris traversal, stack-based pre/in/post-order without recursion.

2,714problems
Learn →
Part III - Hashing & Auxiliary Structures
ij

Heap / Priority Queue

Min/max heap, top-k, median finding, merge k-sorted, Huffman coding.

496problems
Learn →
ij

Trie

Prefix tree for dictionary, autocomplete, spell check, IP routing, XOR max pair.

158problems
Learn →
ij

Monotonic Stack

Next greater/smaller element, largest rectangle in histogram, trapping rain water.

3,426problems
Learn →
ij

Hashmap Patterns

Frequency counting, anagram grouping, subarray sum equals k, longest consecutive sequence.

4,313problems
Learn →
ij

Stack & Queue

Min stack, queue by stacks, circular deque, sliding window max (deque).

1,290problems
Learn →
ij

Counting Patterns

Counting sort, bucket sort, frequency array, cumulative distribution, pigeonhole.

4,313problems
Learn →
ij

K-th Element

Quickselect, median of medians, k-th smallest in sorted matrix, k-th largest in stream.

496problems
Learn →
ij

Monotonic Queue

Deque maintaining monotonic order for sliding window min/max, range min queries.

4,313problems
Learn →
ij

Two Heaps

Median from data stream, sliding window median, IPO capital, schedule tasks.

496problems
Learn →
ij

Bracket Sequences

Valid parentheses generation, longest valid parentheses, minimum add to make valid.

4,313problems
Learn →
ij

Amortized Patterns

Why O(n) operations can cost O(1) each on average (two-pointer, stack, deque).

4,313problems
Learn →
ij

Expression Parsing

Shunting yard, recursive descent, prefix/postfix conversion, basic calculator.

4,313problems
Learn →
ij

Trie XOR

Max XOR pair/subarray using binary trie. Properties of XOR on bits.

4,313problems
Learn →
ij

K-Way Merge

Merge k-sorted arrays/lists, smallest range covering k lists, merge k-sorted iterators.

4,313problems
Learn →
Part IV - Core Algorithms
ij

Dynamic Programming

Memoization, tabulation, state definition, transitions. The universal hammer for optimal substructure.

4,313problems
6 vars
ij

Backtracking

Decision tree exploration, pruning, permutations, combinations, subsets, N-queens.

325problems
Learn →
ij

Greedy

Make the locally optimal choice at each step. Interval scheduling, coin change, Huffman.

0problems
Learn →
ij

Graph

BFS, DFS, connected components, bipartite, DAGs, topological sort, SCC.

1,290problems
6 vars
ij

Shortest Path

Dijkstra, Bellman-Ford, Floyd-Warshall, SPFA, 0-1 BFS, A*.

1,290problems
Learn →
ij

Bitmask DP

DP over subsets using bitmasks. TSP, assignment, graph covering, state space search.

4,313problems
Learn →
ij

Divide & Conquer

Master theorem, merge sort, quick sort, closest pair, maximum subarray (D&C).

1,290problems
Learn →
ij

Knapsack DP

0/1 knapsack, unbounded knapsack, bounded knapsack, subset sum, coin change II.

4,313problems
Learn →
ij

Graph - Advanced

Johnson's algorithm, minimum cost flow, Gomory-Hu tree, dominator tree.

1,290problems
Learn →
ij

Bipartite / Bicoloring

Check bipartite, maximum bipartite matching, König's theorem, Hall's theorem.

1,290problems
Learn →
ij

Coordinate Compression

Map sparse coordinates to dense indices for segment trees, BIT, DP.

4,313problems
Learn →
ij

Topological Sort

Kahn's algorithm, DFS-based sort, course schedule, dependency resolution.

1,290problems
Learn →
ij

Minimum Spanning Tree

Kruskal's, Prim's, Borůvka's, MST verification, second-best MST.

1,290problems
Learn →
ij

Network Flow

Ford-Fulkerson, Edmonds-Karp, Dinic's, max-flow min-cut, circulation.

1,290problems
Learn →
ij

Meet in the Middle

Split the input in half, solve each half, combine results. Subset sum, knapsack, TSP.

4,313problems
Learn →
ij

Convex Hull Trick

DP optimization: line container for max/min queries. Li Chao tree, dynamic CHT.

4,313problems
Learn →
ij

Centroid Decomposition

Decompose tree by centroids for O(log n) path queries. Distance queries, counting paths.

1,290problems
Learn →
ij

Line Sweep

Sweep-line algorithm for interval union, skyline, rectangle area, closest pair.

1,290problems
Learn →
ij

2-SAT

Implication graph, strongly connected components. Boolean satisfiability with 2 variables per clause.

1,290problems
Learn →
ij

Bridges & Articulation Points

Tarjan's algorithm for bridges, articulation points, biconnected components.

1,290problems
Learn →
ij

Min-Cost Max-Flow

Successive shortest augmenting path, potentials, cycle canceling, assignment problem.

1,290problems
Learn →
ij

Flow with Lower Bounds

Circulation with demands, feasible flow with lower/upper bounds, max flow with lower bounds.

1,290problems
Learn →
ij

Bidirectional BFS

Meet-in-the-middle on graphs. Word ladder, 8-puzzle, shortest path in large state spaces.

1,290problems
Learn →
ij

A* Search

Heuristic-guided search for shortest path. Manhattan distance, admissible heuristics.

1,290problems
Learn →
ij

Difference Constraints

System of inequalities reduced to shortest paths. Bellman-Ford on constraint graph.

1,290problems
Learn →
ij

Functional Graphs

Each node has exactly one outgoing edge. Cycle detection, distance to cycle, Josephus.

1,290problems
Learn →
ij

Matching via Flow

Bipartite matching via max flow. Assignment, Hall's marriage, vertex cover, edge cover.

1,290problems
Learn →
ij

Graph Coloring

Chromatic number, greedy coloring, Welsh-Powell, Brooks' theorem, interval graph coloring.

1,290problems
Learn →
ij

Top-K Streaming

Heavy hitters, count-min sketch, reservoir sampling, streaming median, frequent items.

1,290problems
Learn →
ij

Strongly Connected Components

Kosaraju's, Tarjan's algorithm. Condensation DAG, 2-SAT, dominator trees.

1,290problems
Learn →
ij

Graph State Space

Model problems as state transitions on a graph. Water jug, missionaries and cannibals, 8-puzzle.

1,290problems
Learn →
ij

Greedy Intervals

Interval scheduling, interval partitioning, meeting rooms, merge intervals, insert interval.

1,290problems
Learn →
ij

Constructive Algorithms

Build a valid solution step by step. Grid construction, permutation construction, array construction.

1,290problems
Learn →
ij

Backtracking with Pruning

Constraint propagation, forward checking, branch and bound, sudoku, cryptarithmetic.

1,290problems
Learn →
ij

Multi-Source BFS

Enqueue all sources at level 0. Rotten oranges, walls and gates, as far from land as possible.

1,290problems
Learn →
ij

Grid Islands

Number of islands, max area island, number of distinct islands, surrounded regions.

1,290problems
Learn →
Part V - Strings, Sequences & Grid
ij

String Algorithms

String fundamentals: reverse, rotation, comparison, pattern matching basics, anagram detection.

3,426problems
Learn →
ij

String Matching

KMP, Rabin-Karp, Z-algorithm. Find pattern in text, count occurrences, shortest palindrome.

3,426problems
Learn →
ij

Sequences

LIS, LCS, edit distance, longest arithmetic subsequence, wiggle sequence, Russian doll envelopes.

0problems
Learn →
ij

Matrix / Shape

Matrix traversal, rotation, spiral, set zeroes, word search, island perimeter, game of life.

331problems
Learn →
ij

String DP

DP on strings: edit distance, interleaving string, distinct subsequences, decode ways, regular expression.

4,313problems
Learn →
ij

Palindrome Patterns

Longest palindromic substring (Manacher's), count palindromes, palindrome partitioning, break a palindrome.

4,313problems
Learn →
ij

String Hashing

Rolling hash, Rabin-Karp, double hash, detect plagiarism, longest common substring via binary search + hash.

4,313problems
Learn →
ij

Suffix Array

Build suffix array, LCP array, longest repeated substring, number of distinct substrings, longest common substring.

4,313problems
Learn →
ij

Aho-Corasick

Multiple pattern matching automaton. Built on Trie + failure links. Find all occurrences of many patterns in text.

4,313problems
Learn →
ij

Z-Function

Compute Z-array in O(n): longest substring starting at i that matches prefix. String periodicity, pattern matching.

4,313problems
Learn →
ij

Manacher's Algorithm

Longest palindromic substring in O(n) using symmetry expansion and center caching.

4,313problems
Learn →
ij

Suffix Automaton

Minimal DFA accepting all suffixes of a string. Count distinct substrings, longest common substring, lexicographically smallest.

4,313problems
Learn →
ij

String Rotations

Lexicographically minimal rotation (Booth's), string matching on rotation, periodic strings.

4,313problems
Learn →
ij

Lyndon Factorization

Split string into Lyndon words (non-increasing). Duval's algorithm. Minimal rotation, necklace computation.

4,313problems
Learn →
ij

String Construction

Build smallest/greatest string under constraints. Lexicographically smallest after swaps, K-th lexicographically smallest.

4,313problems
Learn →
ij

String Window Patterns

Sliding window applied to strings: anagram substrings, min window substring, substring concatenation.

4,313problems
Learn →
Part VI - Math & Discrete
ij

Math

Number theory, combinatorics, Euclidean gcd/lcm, modular arithmetic, prime sieve.

9,632problems
Learn →
ij

Bit Manipulation

XOR tricks, bit hacks, Brian Kernighan, subset enumeration via bits, gray code, bitmask DP.

2,868problems
Learn →
ij

Combinatorics

Permutations, combinations, stars and bars, inclusion-exclusion, generating functions.

0problems
Learn →
ij

Game Theory

Nim, Grundy numbers, Sprague-Grundy theorem, impartial games, minimax.

0problems
Learn →
ij

Geometry

Convex hull, line intersection, polygon area, point in polygon, rotating calipers.

0problems
Learn →
ij

Number Theory

Extended Euclidean, modular inverse, CRT, Euler's totient, Fermat's little theorem, Miller-Rabin, Pollard's Rho.

9,632problems
Learn →
ij

Probability DP

Expected value DP, Markov chains, probability distributions, random walk, gambler's ruin.

4,313problems
Learn →
ij

Ternary Search

Find peak of unimodal function. Divide into three parts, discard one. Bitonic arrays, convex functions.

9,632problems
Learn →
ij

Fast Fourier Transform

Polynomial multiplication, convolution, big integer multiplication, signal processing.

9,632problems
Learn →
ij

Sprague-Grundy Theorem

Grundy numbers for impartial games. Compute mex, XOR combined games, game of Nim, Kayles, subtraction games.

9,632problems
Learn →
ij

Chinese Remainder Theorem

Solve system of linear congruences. Garner's algorithm for big integers. RSA-related problems.

9,632problems
Learn →
ij

Convex Hull

Graham scan, Andrew's monotone chain, Jarvis march, dynamic convex hull, convex hull of a polygon.

9,632problems
Learn →
ij

Inclusion-Exclusion

Count unions of sets, derangements, coprime count, principle applied to number theory and combinatorics.

9,632problems
Learn →
ij

Catalan Numbers

Counting: BSTs, parentheses, Dyck paths, triangulations, non-crossing partitions. Recurrence and closed form.

9,632problems
Learn →
ij

Josephus Problem

Find the last remaining position when every k-th is eliminated. O(n) DP, O(k log n) for large n.

9,632problems
Learn →
ij

Sieve Variants

Eratosthenes, linear sieve, segmented sieve, prime counting, divisor count, totient sieve, Mobius sieve.

9,632problems
Learn →
ij

Burnside's Lemma

Count distinct objects under group action. Orbit-counting, necklace/bracelet enumeration, Polya enumeration.

9,632problems
Learn →
ij

Gray Code

Binary representation where consecutive values differ by one bit. Sequence generation, n-queens bitset, subset generation.

9,632problems
Learn →
ij

Gaussian Elimination GF(2)

Solve linear systems over GF(2). XOR basis, linear basis of array, find if target reachable, maximum XOR subset.

9,632problems
Learn →
ij

Lucas' Theorem

Compute large binomial coefficients modulo prime. nCr mod p using base-p digits. Digit DP and combinatorics intersection.

9,632problems
Learn →
ij

Lattice Paths

Count/generate monotonic paths on integer lattice. Delannoy numbers, with/without obstacles, with/without diagonals.

9,632problems
Learn →
ij

Advanced Counting DP

Combinatorial DP beyond basics: Stirling numbers, Eulerian numbers, Bell numbers, partition DP, set partition.

9,632problems
Learn →
ij

Rotating Calipers

Width/diameter of convex polygon, minimum bounding rectangle, distance between convex polygons. O(n).

9,632problems
Learn →
ij

Carry DP

Digit DP where carry propagates through positions. Count numbers with sum of digits equal, etc.

9,632problems
Learn →
ij

Random Walk

Expected time to absorption, probability of reaching boundary, gambler's ruin, 1D/2D walk, drunkard's walk.

9,632problems
Learn →
ij

Number Tricks

Numerical properties, digital root, self numbers, happy numbers, narcissistic numbers, Kaprekar, Ulam, perfect numbers.

9,632problems
Learn →
Part VII - Advanced Topics
ij

Linear Algebra

Matrix operations, Gaussian elimination, determinant, rank, eigenvalues, linear transformations.

0problems
Learn →
ij

Numerical Methods

Newton's method, binary search for roots, integration, differentiation, gradient descent, Monte Carlo.

0problems
Learn →
ij

Scheduling

Job sequencing, interval scheduling, CPU scheduling, task scheduling with dependencies, resource allocation.

0problems
Learn →
ij

Shapes / Geometry

Area/perimeter/volume of geometric shapes, union/intersection of shapes, packing, tiling, cutting stock.

331problems
Learn →
ij

Miscellaneous

Cache policies (LRU, LFU, ARC), OOP design, system design, concurrency problems, brainteasers.

0problems
Learn →
ij

Design Patterns

Singleton, factory, observer, strategy, decorator, adapter, command, iterator. OOP design in coding interviews.

0problems
Learn →
ij

Sorting Algorithms

Quick sort, merge sort, heap sort, counting sort, radix sort, bucket sort, tim sort, intro sort.

4,313problems
Learn →
ij

Simulation

Implement the problem description faithfully. Text processing, game simulation, protocol implementation.

0problems
Learn →
ij

Matrix Exponentiation

Linear recurrences via fast matrix power. Fibonacci in O(log n), linear DP acceleration.

9,632problems
Learn →
ij

Randomized Algorithms

Randomized quickselect, reservoir sampling, Fisher-Yates shuffle, Monte Carlo methods, Miller-Rabin.

4,313problems
Learn →
ij

Multiset & Ordered Set

Order statistic tree, sorted container, balanced BST simulation. K-th element, count of elements in range.

4,313problems
Learn →
Part VIII - Cross-Topic Deep Dives
ij

BFS vs DFS

When BFS beats DFS and vice versa. Shortest path, topological, bipartite, connected components, backtracking.

1,290problems
Learn →
ij

Interval Problems

Interval union, intersection, overlap, covering, partition, scheduling. Sweep-line, greedy, segment tree.

0problems
Learn →
ij

DP on Trees

Tree DP: diameter, paths, subtree aggregates, rerooting DP, knapsack on tree, tree matching.

2,714problems
Learn →
ij

Union-Find (DSU)

Disjoint set union with path compression and union by size. Dynamic connectivity, Kruskal, connected components.

1,290problems
Learn →
ij

Digit DP

DP on number digits with tight/loose bounds. Count numbers with property in range. Sum of digits, divisible by k.

4,313problems
Learn →
ij

Interval DP

DP over intervals: matrix chain multiplication, burst balloons, palindrome partitioning II, stone game, optimal BST.

4,313problems
Learn →
ij

Grid DP

DP on 2D grids: unique paths, minimum path sum, dungeon game, cherry pickup, triangle, falling path sum.

4,313problems
Learn →
ij

State Machine DP

DP with explicit states. Best time to buy/sell stock, paint house, student attendance, k transactions.

4,313problems
Learn →
ij

Recursion + Memoization

Top-down DP, memoization patterns, recursion tree optimization, stack depth management, tabulation conversion.

4,313problems
Learn →
ij

Grid Patterns

Neighbor iteration, matrix prefix sum, BFS/DFS on grid, island patterns, shortest distance, multi-source.

1,290problems
Learn →
ij

Fenwick Tree (BIT)

Range sum/product queries with point updates. LIS count, inversion count, order statistics, offline queries.

4,313problems
Learn →
ij

Heavy-Light Decomposition

Decompose tree into heavy/light paths for path queries with segment tree. Path sum, max, min, update.

1,290problems
Learn →
ij

Euler Tour (ETT)

Flatten tree into array via Euler tour. Subtree queries become range queries. LCA via RMQ, subtree aggregates.

1,290problems
Learn →
ij

Mo's Algorithm

Offline query processing with sqrt decomposition. Sort queries by block, maintain pointer movement. Range queries.

4,313problems
Learn →
ij

XOR Basis / Linear Basis

Basis of numbers under XOR. Maximum XOR subset, minimum XOR subset, K-th smallest XOR, rank of XOR space.

4,313problems
Learn →
ij

Euler Path / Circuit

Hierholzer's algorithm for Eulerian path. Chinese postman problem, de Bruijn sequence. Hierholzer, Fleury.

1,290problems
Learn →
ij

Divide & Conquer DP

DP optimization: monotone opt property (quadrangle inequality). DP[i][j] = min over k < j of DP[i-1][k] + C[k][j].

4,313problems
Learn →
ij

Square Root Decomposition

Partition array into sqrt blocks. Batch queries, lazy rebuild. Range sum/update, mode query, k-th smallest in range.

4,313problems
Learn →
ij

Persistent Segment Tree

Versioned segment trees. K-th smallest in range, count distinct in range, sum/update across versions.

4,313problems
Learn →
ij

Treap (Randomized BST)

Randomized BST with heap property. Split/merge operations. Range reverse, lazy propagation, order statistics, implicit treap.

4,313problems
Learn →
ij

Offline CDQ Divide & Conquer

CDQ divide-and-conquer for multi-dimensional offline queries. 3D partial order, dynamic convex hull, DP optimization.

4,313problems
Learn →
ij

Bitset Operations

std::bitset / BigInt manipulation for DP optimization. Bitset knapsack, graph reachability, matching, subset queries.

4,313problems
Learn →
ij

Slope Trick

DP optimization for convex piecewise-linear functions. Priority queue management. Tree DP, grid DP, scheduling DP.

4,313problems
Learn →
ij

Segment Tree Beats

Segment tree with min/max operations that break standard lazy. Range chmin/chmax, range sum queries in O(n log n).

4,313problems
Learn →
ij

Balanced DP

DP with equilibrium constraints. Balance brackets, load balancing, fair division, partition with balance target.

4,313problems
Learn →
ij

Profile DP (DP on Broken Profile)

DP over row/column with state profile. Bitmask DP on grids, tiling problems, crosswords, domino tilings.

4,313problems
Learn →
ij

Aliens Trick (Lagrange DP)

DP optimization using Lagrangian relaxation. Attach penalty lambda for constraint, binary search lambda. k-trades, partition.

4,313problems
Learn →
ij

Arithmetic DP

DP on arithmetic properties. Sum of digits, divisibility, carry DP, digit DP variants with arithmetic constraints.

4,313problems
Learn →
ij

Subsequence Counting

Count distinct subsequences, number of subsequences with given sum/product, subsequence pattern matching.

4,313problems
Learn →
ij

Sliding Window - Advanced

At-most-k trick, exactly-k count formula, multiple-pointer windows, deque optimization for range max/min.

4,313problems
Learn →
ij

2D Prefix Sum

Prefix sum on 2D grid. Range sum queries, submatrix sum, count submatrices with sum ≤ k.

4,313problems
Learn →
ij

DP with Deque Optimization

Sliding window DP optimization: DP[i] = max over j in window of DP[j] + f(j,i). Range min/max of DP values.

4,313problems
Learn →
ij

Stock Trading

Best time to buy/sell with 1, 2, k transactions. Cooldown, transaction fee, frozen state. State machine DP.

4,313problems
Learn →
ij

DP Space Optimization

Rolling array, 1D to O(1) space, Knuth optimization, monotone queue optimization, divide & conquer optimization.

4,313problems
Learn →
ij

String Window Patterns

Sliding window applied to strings: anagram substrings, min window substring, substring concatenation, find all anagrams.

4,313problems
Learn →