##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
Explore individual topics with detailed lessons and practice problems.
Recursion from scratch. You'll learn the two parts of every recursive function and trace execution step by step.
You know recursion. Now see how memoization and tabulation turn exponential solutions into polynomial ones.
Recursion from scratch. You'll learn the two parts of every recursive function and trace execution step by step.
Why recursion matters
Self-calling functions
Stopping condition
Breaking down problems
Classic first recursion
Test your understanding
What's the simplest?
Breaking it down
Writing the code
Tracing factorial(4)
How calls stack up
Testing stack understanding
summary
New application
Test your understanding
Single digit
Last digit + rest
Complete solution
Tracing the calls
Greatest Common Divisor
Knowledge check
Why modulo works
When to stop
The Euclidean algorithm
Three lines of code
Tracing Euclid's algorithm
Manual recursion exercise
Computing x^n
Knowledge check
The slow way
Halving the problem
When to stop
The efficient code
Tracing fast exponentiation
Testing power optimization
summary
The general approach
Pitfalls to avoid
When to use each
When to use which
Preview of memoization
What we learned
You know recursion. Now see how memoization and tabulation turn exponential solutions into polynomial ones.
The power of optimization
LC 509 classic
Two starting points
Two calls
Direct translation
Explosion of calls
Same work repeated
O(2^n) disaster
Remember results
Test your understanding
The bridge
Caching results
Starting from the top
Adding memory
Three extra lines
O(n) now!
O(n) cost
LC 70 Fibonacci disguise
DP basics
Apply the pattern
The code
Knowledge check
Pattern recap
Building from ground up
Why called bottom-up
Iterative solution
Only keep what you need
Most efficient
When to use each
Your first cost problem
What dp[i] means
Choose cheaper path
Full solution
Knowledge check
LeetCode 91
One or two digits
Leading zeros
Ways to decode
Two choices
The code
What we learned
Apply DP to linear problems. House Robber, Boredom, and Consecutive Subsequence. Each problem uses a 1D state array.
One state variable
The transition
The four-step blueprint
The classic problem
Why odd/even sums fail
Setting up the state
The take-or-skip choice
Starting conditions
Reading the answer
Putting it together
Testing DP state design
summary
A similar structure
First 1D DP problem
Take or skip each value
Starting conditions
Reading the answer
Complete solution
Testing problem reduction
Large values, same pattern
Learn how to define the DP state for finding the longest consecutive subsequence.
Extra requirements for state definition.
Learn the transition formula: extend subsequences by linking consecutive values.
Learn how to initialize the DP values before processing the array elements.
Learn how to find the answer and rebuild the subsequence
Putting it all together
Testing LIS variant
Reducing DP dimensions
Patterns from both problems
The common structure
Manual DP exercise
Test your understanding
Understand the block cutting problem where each block has a length marker
From intuition to states
Learn how to define the DP state using prefix arrays
Learn how to extract the final answer from the DP state
Right End Block
Left End Block
Apply the pattern
Preview of 2D DP
What you learned and what comes next
When one dimension is not enough. You'll design DP states with multiple parameters for grids and strings.
Why multi-dimensional DP
The limitation
Core concept
Two parameters
Pattern reminder
Knowledge check
Codeforces 478D
Understanding constraints
First observation
Two parameters
Color choice
Starting point
Valid configurations
The code
summary
AtCoder DP-H
The setup
What dp[i][j] means
Coming from above or left
Blocked cells
Starting point
The code
summary
CSES 1639
Insert, delete, replace
Prefix to prefix
Match or operate
Empty strings
The code
summary
Counting paths in a grid
Understanding the grid
What dp[i][j] means
From above or left
Complete solution
Find cheapest path
Minimum cost to cell
Choose cheaper path
Complete solution
What we learned
You've built DP on sequences and grids. Now face capacity constraints and learn to pick or skip items.
The Goal
The classic
The trap
Two dimensions
Empty foundations
Take or skip
Reading the table
The code
Tracing the algorithm
summary
Finding which items were taken
Knowledge check
AtCoder DP D
When weights explode
AtCoder DP E
The constraint trap
Swap dimensions
Value as index
Minimum weight
The code
Value-based DP trace
When to swap
Choosing the right approach
Knowledge check
Items repeat
Infinite copies
One dimension
Reuse allowed
The code
Unlimited items trace
Simplification
Comparing variants
Apply unbounded
Classic unbounded example
Knowledge check
The framework
Knapsack in disguise
It's a knapsack
Max pages for budget
Applying the pattern
Apply 0/1 knapsack
Preview of variations
What we learned
You know the core 0/1 knapsack. Now learn unbounded knapsack, bounded copies, and value-based state design.
What you'll learn
The shift
LeetCode 416
Finding the pattern
True or false
The code
Tracing subset sum
summary
Finding the actual subsets
Knowledge check
LeetCode 494
The math
The code
Signs to subsets
Testing the reduction
The shift
LeetCode 518
The trap
The fix
The code
Counting combinations
summary
Understanding loop order
Knowledge check
The constraint
Classic variation
The problem
The trick
The code
Limited quantities
Why it works
Knowledge check
Multiple limits
LeetCode 474
3D state
The code
2D knapsack trace
LeetCode 1049
The observation
The code
Hidden subset sum
Understanding the transform
Apply counting pattern
Preview of 2D grid DP
Decision guide
What we learned
You know knapsack patterns. Now you need a tool that speeds up range computations. Prefix sums turn O(n) range queries into O(1).
The Goal
Why we need this
Loop every query
The definition
One pass
The formula
The code
Tracing the algorithm
Getting indices right
Knowledge check
Query range sums fast
Applying the technique
Two prefix arrays
Prefix[r] - prefix[l-1]
Sorted and original
Applying prefix sums
Two array variant
Understanding the tradeoff
Complete solution
The code
HashMap prefix counting
Count with frequency
The code
HashMap technique trace
Special case of k=0
Knowledge check
Prefix and suffix products
Two directions
Prefix and suffix products
Handling zeros
One output array
2D prefix sum queries
Inclusion-exclusion
2D prefix sums trace
Counting with target sum
The code
Knowledge check
Kadane connection
Kadane's algorithm
Comparing approaches
summary
Recognizing the pattern
Preview of LIS
What we learned
You've learned prefix sums. Now find the longest increasing subsequence and optimize with binary search.
The Goal
The definition
Classic DP problem
The trap
What dp[i] means
The recurrence
The code
Tracing the O(n^2) algorithm
Finding the actual subsequence
Why ending at i
Knowledge check
summary
The optimization idea
O(n log n) code
O(n log n) algorithm trace
Understanding the tails array
Knowledge check
Counting all LIS
Length and count
The code
Counting subsequences
When counts add up
2D LIS variant
2D LIS reduction
LIS on string predecessors
LIS on strings
Knowledge check
LIS with divisibility
Hidden pattern
The code
LIS with divisibility
Recognizing the pattern
Classic variation
Sum instead of length
The code
Weighted LIS
Finding the optimal subsequence
Bidirectional LIS
Forward and backward
The code
Two-directional LIS
Understanding the approach
LIS application
LIS for non-decreasing
Recognizing LIS problems
Understanding space usage
Preview of LCS and Edit Distance
What we learned
You know LIS with 1D states. Now work with two sequences simultaneously. LCS and Edit Distance are the basis of all string comparison algorithms.
The Goal
Two sequences
LeetCode 1143
The 2D table
Match or skip
The code
Tracing the algorithm
Knowledge check
Finding the actual sequence
summary
Reducing memory
LeetCode 712
Cost instead of count
The code
Weighted LCS variant
LeetCode 72
Three choices
Minimum cost
The recurrence
The code
Tracing transformations
Finding the operations
Knowledge check
summary
Recognition tips
LeetCode 516
LCS with itself
LeetCode 583
LeetCode 115
Counting occurrences
Knowledge check
LeetCode 1092
Length formula
The code
Building from LCS
LeetCode 44
Boolean 2D DP
The code
Pattern matching DP
Preview of Interval DP
What we learned
You've compared sequences with LCS. Now solve problems where the answer depends on breaking ranges apart.
Why ranges need special thinking
Range-based states
Range definition
Dividing ranges
Why length matters
Testing core concepts
Entry problem
Endpoints determine structure
The 2D table
Match or skip
The code
Tracing the algorithm
Understanding the recurrence
summary
Classic interval DP
Understanding dimensions
What dp[i][j] means
Try all split points
The code
Tracing optimal splits
Finding optimal parenthesization
Understanding the cost
summary
LeetCode 312
Think about last
Open intervals
Last balloon
The code
Tracing the trick
Why think backwards
summary
LeetCode 132
Precompute + solve
The code
Minimum cuts trace
Finding all partitions
When to use it
Interval DP game
Game theory meets intervals
Difference formulation
Polygon DP
MCM variant
Recognizing the pattern
Preview of Tree DP
What we learned
You've done DP on arrays and grids. Trees add a new dimension: states live at nodes, not indices.
The Goal
The building block
Dp[node] from children
Children before parents
Knowledge check
CSES 1131
Paths pass through nodes
Deepest path down
Single DFS
Tracing the algorithm
Reconstructing the diameter
Knowledge check
LeetCode 337
Rob or skip each node
Two values per node
Return a pair
Tracing the two-state DP
Extending to more states
Knowledge check
Why rerooting?
LeetCode 834
Moving the root
Down then up
The formula
Tracing rerooting
Understanding the efficiency
Classic tree DP problem
Handling negative values
Understanding the transitions
Finding centroids
Topological peeling
Path maximum tracking
Top-down DFS pattern
Choosing the right direction
Minimum vertex cover variant
Three-state DP
Post-order with state
Why this greedy works
Designing effective states
Generalizing beyond trees
Preprocessing for fast queries
Preview of Digit DP
What we learned
You've handled linear, 2D, and tree states. Bitmask DP tracks which elements you've used in a subset.
The Goal
Subset as integer
The tools you need
Concrete usage
Enumeration patterns
Knowledge check
Dp[mask] indexed by subsets
Recognition tips
Knowledge check
Entry problem
Bitmask as subset
The code
Knowledge check
LeetCode 1879
Process in order
Dp[mask] alone
O(n × 2^n)
Knowledge check
Count routes, bitmask DP
Visited set + current city
Dp[mask][last]
Add next city
O(n² × 2^n)
Knowledge check
LeetCode 698
Track partial sum
The code
A new problem type
The O(3^n) way
Build subsets bit by bit
Include or exclude bit i
Knowledge check
Drop the second dimension
The code
CSES 1654
Subset relationships
Three SOS passes
The dual problem
Knowledge check
Recognition and practice
summary
What we learned
Counting numbers in huge ranges seems impossible. Digit DP builds answers digit by digit.
What you'll learn
Digit-by-digit processing
The key constraint
Understanding the constraint
Handling shorter numbers
When zeros matter
State template
From [L,R] to prefix
LeetCode 902
Understanding the constraints
What dp[pos][tight] means
Picking valid digits
The code
Tracing the algorithm
summary
Handling tricky inputs
LeetCode 2376
Tracking used digits
Adding the mask
Checking the mask
The code
Tracing distinct digits
summary
Why bitmask works
LeetCode 600
Working in binary
Tracking previous bit
Avoiding 11
The code
Tracing with previous digit
summary
Generalizing the constraint
Core idea
Classic digit DP variant
Memoization details
Analyzing state space
Adjacent digit constraint
Handling started flag
Comparing two numbers
Recognizing the pattern
Preview of Game Theory DP
What we learned
You've used DP for optimization. Game Theory DP handles two players taking turns with optimal moves.
The Goal
Both play perfectly
The foundation
State classification
My best against their best
Knowledge check
LeetCode 486
Score difference trick
Dp[i][j] for range
Left or right choice
The code
Tracing the game
When does first move help?
Knowledge check
LeetCode 1140
Track M parameter
Dp[i][M]
With suffix sums
Tracing with M parameter
Exploring modifications
Knowledge check
LeetCode 464
Bitmask meets game theory
Dp[mask]
Memoization with bitmask
Tracing with bitmask
Understanding the bitmask
Knowledge check
summary
The classic game
Beyond brute force
Division-based moves
Proving the pattern
Perfect square moves
Efficient computation
String transformation game
Combining independent games
Understanding nimbers
Two-agent chase
Handling draws
Three outcomes
Recognizing and solving
Beyond win/lose
Multi-agent games
Preview of Probability DP
What we learned
You know deterministic DP. Now handle randomness. Compute probabilities and expected values.
What you'll learn
Expected values
Average outcome
Understanding expectation
Weighted edges
Weighted sum
A powerful property
LeetCode 688
Understanding the grid
What dp[r][c][k] means
Eight directions
Boundaries
The code
Tracing the transitions
summary
Expected value variant
LeetCode 576
Position and moves
Four directions
The code
Counting paths with probability
summary
Counting vs probability
LeetCode 808
Scaling trick
Remaining amounts
Four operations
The code
Understanding the approximation
summary
Why the threshold works
Core idea
Card drawing probability
Sliding window optimization
Understanding the constraint
Geometric probability
Probability with different coins
Space optimization
Constrained sequences
State design choices
When expectation diverges
Recognizing the pattern
Preview of D&C Optimization
What we learned
Your DP is too slow. Learn D&C optimization and Knuth optimization based on the quadrangle inequality.
What you'll learn
The problem
The condition
Testing the concept
The proof
Why QI helps
Two techniques
Core idea
Step by step
Tracing the divide and conquer
The analysis
Why O(n log n)
Mental model
Codeforces 321E
State and transition
The proof
The code
Tracing the optimization
summary
Verification techniques
Core idea
Why it works
Processing by length
Tracing the double bound
The amortized analysis
Mental model
Classic application
State and transition
The proof
The code
Tracing the classic example
summary
Classic Knuth problem
Handling the edge cases
Line breaking optimization
Identifying the DP type
Partitioning with cost
Computing costs efficiently
When to use which
Choosing the right one
What to avoid
Recognizing inapplicable cases
Advanced applications
Core idea
Avoiding common bugs
Pattern recognition exercise
Preview of Convex Hull Trick
What we learned
You know QI-based optimizations. Now meet recurrences as lines and query minimum/maximum with CHT.
The Goal
The problem
The building block
The transformation
Identifying CHT applicability
Lines in a plane
The structure
Understanding the geometry
The pruning
Core idea
The simple case
Data structure
Tracing the deque maintenance
Maintaining the hull
Why we pop from back
Finding the best line
Tracing a query
Amortized analysis
Mental model
CF 319C
State and transition
The transformation
The conditions
The code
Tracing the full solution
summary
Handling arbitrary order
The general case
O(log n) queries
Alternative structure
Understanding the structure
Choosing the right structure
What to avoid
Classic CHT problem
Handling maximization
Another classic
Deriving the linear form
Higher dimensions
Recognition
When to apply CHT
Practical advice
Preview of Monotonic Queue
What we learned
You know CHT for lines. Monotonic queues handle sliding window min/max in O(1) per query.
Deque optimization for sliding window DP
When naive DP times out
Sorted deque
Understanding the property
Why old candidates become useless
Add and remove
Tracing the operations
Knowledge check
LeetCode 239
Why sorting fails
Decreasing queue
The code
Detailed trace
LeetCode 1696
State and transition
Recognizing the pattern
The code
DP with window constraint
Knowledge check
Dynamic window bounds
LeetCode 1425
The twist
The code
Maximum sum with gap constraint
LeetCode 862
Setting up the problem
Monotonic increasing queue
The code
Tracing the prefix sum approach
Knowledge check
Why prefix sums help
Pattern recognition
2D extension
Sliding window connection
Pattern recognition
Choosing the right queue
Choosing the right variant
With absolute diff constraint
Two deques pattern
Query order matters
When to use what
Identifying applicable problems
Reusable code structure
Preview of Aliens Trick
What we learned
Face 'exactly K' constraints that add a dimension? Aliens Trick uses penalties to reduce complexity.
Removing the K dimension
Exactly K constraint
Penalty parameter
Understanding the trade-off
The transformation
Finding the right penalty
Finding the right penalty
Convexity requirement
When Aliens works
Counting segments used
Counting elements used
Knowledge check
USACO Platinum
Why diminishing returns
The formulation
The code
Tracing the solution
Codeforces 674C
Before optimization
Removing the k dimension
Going even faster
Combining with CHT
Codeforces 739E
Two penalties
The code structure
Two-dimensional application
Knowledge check
Multi-constraint handling
The namesake
Simplifying the problem
Without the trick
Aliens + CHT
High-level structure
The hardest application
Pattern recognition
Non-convex cases
What can go wrong
Avoiding common bugs
When to consider this trick
Preview of Slope Trick
What we learned
DP with absolute value costs creates piecewise linear functions. Slope Trick tracks only the slopes.
Why Slope Trick exists
Shape of costs
Understanding the structure
Critical breakpoints
Tracking breakpoints
Storing breakpoints efficiently
Knowledge check
Understanding the structure
CF 713C
Making it non-decreasing
Convex function
Double-push trick
Full solution
Tracing the heap operations
Variant with strict inequality
CF 865D
Retroactive decisions
Slope function analog
Greedy with heap
Tracing the greedy insight
Understanding the regret mechanism
CSES 2132
Convexity preservation
Maintaining breakpoints
Max-heap solution
Increasing array variant
Advanced technique
How prefix min affects the function
Generalized version
Scheduling variant
Pattern recognition
Recognizing the pattern
What to avoid
Avoiding mistakes
Why it's fast
Understanding the efficiency
Another variant
Non-convex extensions
Efficient global shifts
IOI variant
Comparing techniques
How to improve
Identifying applicable problems
Reusable structure
Query the function at points
Preview of Broken Profile DP
What we learned
Grid tiling with dominoes. Process row by row, using a bitmask for the boundary between rows.
Grid tiling with profiles
Column boundary states
Understanding the boundary
Compact state
How to represent states
Column to column
How masks change
Knowledge check
CSES 2181
What DP tracks
Recursive placement
Combining paths
Full solution
Tracing the classic problem
Generating valid transitions
Knowledge check
UVa 10918
Manual enumeration
Pattern from profiles
Recurrence solution
Non-standard grid
Recurrence vs DP
Complexity considerations
LeetCode 790
Three profile types
Tile placement choices
Final formula
Finding the pattern
DP or recurrence
Mixed tile shapes
Knowledge check
Non-tiling variant
Path DP variant
Beyond dominoes
Problem recognition
When to apply this technique
You've completed the DP course
Time and space
Understanding the bounds
Pitfalls to avoid
Debugging tips
What we learned