##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
Explore individual topics with detailed lessons and practice problems.
Terminology, representations (adjacency list/matrix/edge list), graph properties, and complexity analysis.
Welcome
Intuition
Cities and Roads
Users and Friendships
Applications
The "Dots"
The "Lines"
Speaking Math
Two-way streets
One-way streets
Mental Check
How to tell the computer?
The Grid Approach
Seeing the Grid
Why we rarely use it
The Efficient Approach
Seeing the Lists
Memory Usage
Vectors to the rescue
vector adj[N]
Code Snippet
Code Snippet
Node Popularity
In and Out
LeetCode 997
Understanding the Rules
From English to Graph
How to solve it
Writing the Code
LeetCode 1791
Using Degrees
Pure Logic
O(1) Solution
Writing the Code
Codeforces 330B
What we learned
Recursive and iterative DFS, discovery/finish times, DFS tree, and back edges.
The concept of exploring
(LeetCode 133)
How DFS works
(Hash map tracks copies)
Why do we call it that?
(Recursive copy pattern)
The nature of DFS
(Python solution)
The Infinite Loop
Graph change strategy
The Chalk Mark
Step-by-Step
Memorize this
Starting the engine
Dry Run
LeetCode 841
Translating to Graphs
Using DFS
Coding it
Broken Graphs
How to find them all
The Loop
LeetCode 547
Adjacency Matrix Trap
The Code
A simpler graph
The Parent Trick
The Backpack
Codeforces 580C
What to carry?
Updating the State
Coding the logic
How fast is it?
Memory usage
What we learned
Level-order traversal, unweighted shortest path, multi-source BFS, and BFS applications.
Why we need something else
BFS Intuition
Stack vs Queue
Level by Level
Setup
Initialization
The Loop
The Logic
The Distance Array
LeetCode 1091
Adapting the Graph
Storing Coordinates
A Pro Tip
CSES Problem Set
Breadcrumbs
Backtracking
Coding the Path
Graphs in disguise
Seeing the Graph
The hard part
LeetCode 127
LeetCode 994
Start from all sources
Level-by-level spread
The code
Multi-source pattern
LeetCode 542
Reverse the perspective
BFS from all zeros
The code
Distance to nearest source
Time and Space
When to use what?
When to use which BFS
What we learned
Implicit graphs, 4/8-connectivity, island counting, and boundary fill problems.
Theory vs Practice
Visualizing Flood Fill
LeetCode 733
DFS or BFS?
The Chain Reaction
Coding the Solution
From Pixels to Geography
LeetCode 200
Find and Erase
Sinking the Island
Coding the Sinking Strategy
The Impossible Schedule
DFS Recursion Stack
State Management
Walking the path
Starting from many points
LeetCode 463
Count exposed edges
Count, do not traverse
Edge counting code
Not all grid problems need DFS
DFS with size tracking
DFS returns size
Recursive area calculation
LeetCode 695
DFS as a calculator
What we learned
You know BFS and can traverse graphs. Some graphs split into two groups with no same-group edges.
The Goal
Core definition
The visual test
Two disjoint sets
Where they appear
Why some graphs fail
See the contradiction
Knowledge check
The plan
Level-by-level coloring
Recursive approach
Multiple components
LeetCode 785
Adjacency list
Tracking state
Same color neighbors
Handling all components
Step by step
The code
Trace example
When it fails
summary
Knowledge check
LeetCode 886
The party problem
It's bipartite!
Edge list to adj list
One-indexed vs zero-indexed
Same core logic
The code
Trace example
summary
Knowledge check
CSES
Competitive style
Print the teams
Same algo, new output
Step by step
The code
Trace example
summary
Alternative approach
When to use each
What goes wrong
Analysis
Knowledge check
Matching preview
What we learned
Tree properties (N-1 edges, unique paths), rooting trees, parent/child relationships, and tree traversals.
Formal Definition
Gravity matters
Changing perspective
DFS Simplification
The Parent Pointer
Measuring distance
LeetCode 104
Recursive Definition
Coding it
The Pattern
Count employees under each manager
Team size calculation with DFS
Code solution
Longest path in a tree
Find the diameter of a binary tree
Every path has a highest point
Recursive height with diameter update
Complete implementation
Double BFS for general trees
Tree Diameter (CSES)
Pick node, find furthest, repeat
BFS helper function
Calling helper twice
Node minimizing max distance
Find roots that minimize tree height
Topological peeling algorithm
BFS-like leaf removal
Check if two trees are identical
Compare nodes recursively
Recursive comparison logic
Code solution
Key patterns for tree comparison
Mirror a binary tree
Swap children recursively
DFS inversion approach
Code solution
Tree modification patterns
Trees are mastered
Finding tree diameter with two-BFS and DP methods, computing tree center and radius, and solving all-nodes distance queries with rerooting DP.
The Goal
Longest possible path
Network analysis applications
Try all pairs
Start anywhere, go far twice
Intuition behind the proof
Code structure
Knowledge check
CSES 1131
Apply two-BFS directly
Step by step
Pseudocode and code
Example trace
What you learned
Alternative diameter method
Depth through each node
Recursive DFS
When to use each
Knowledge check
LeetCode 543
Use DP method
Recursive DFS
Python solution
summary
The most central node
Peeling leaves iteratively
Middle of longest path
Measuring centrality
Knowledge check
CSES 1132
Reuse diameter endpoints
Three BFS approach
Pseudocode
Example trace
core idea
CSES 1133
Rerooting DP technique
Two-pass DFS
Python code
Example trace
Rerooting pattern
Knowledge check
Different distance queries
What to avoid
What we learned
Processing trees from leaves to root. Aggregating subtree values. Include/exclude patterns and path optimization.
The Goal
Each subtree is a tree
Bottom-up computation on trees
Post-order traversal pattern
Simplest aggregation problem
Knowledge check
What does dp[node] represent
Sum, max, count patterns
Linear in node count
Picking a root matters
CSES 1674
Subtree size minus one
Sum of child subtrees
Single DFS pass
Code with adjacency list
Example tree trace
Subtree aggregation
Knowledge check
Two states per node
Combining child states
LeetCode 337
Two values per node
Include or exclude logic
Null nodes return zero
DFS returning pair
Example tree trace
Include/exclude on trees
Knowledge check
Paths through nodes
Pick two best branches
LeetCode 124
Max downward path from node
Path through node vs from node
Skip negative branches
DFS with global max
Code with global variable
Example tree trace
Two values pattern
Knowledge check
Computing for all roots
What breaks your solution
Why trees are simpler
Problem recognition patterns
What we learned
All-pairs shortest paths. Dynamic programming on graphs. Finding distances between every pair of nodes.
(All-pairs shortest paths)
Finding every pair's distance
(Running Dijkstra n times)
Paths through intermediate ...
(Using vertices 0 to k)
(Overwriting in place)
(Correctness depends on order)
(Three nested loops)
(Cubic in vertices)
(Unlike Dijkstra it works)
(Checking the diagonal)
(Storing next hops)
Reachability instead of dis...
(vs running Dijkstra n times)
(CSES 1672 walkthrough intro)
(All-pairs in one shot)
(Taking the minimum weight)
(Using adjacency matrix)
(Step-by-step trace)
(Precomputation wins)
LeetCode 1334 walkthrough i...
(Two-step approach)
(Looping through distances)
(Using Floyd-Warshall)
(LeetCode example trace)
Post-processing distance ma...
(Mistakes to avoid)
(Two ways to handle negatives)
(Sparse graphs with negatives)
(When n³ is acceptable)
(Using 2D array efficiently)
(Avoiding overflow)
(Symmetric distance matrix)
(Minimax and maximin paths)
(Build your skills)
(What you learned)
Priority queue implementation, lazy deletion, proof of correctness, and optimizations.
Why BFS is not enough for weighted graphs
Edge weights and their meanings
Dijkstra's key insight
Efficient implementation with min-heap
Initialization and data structures
Processing nodes in order
Updating distances through edges
Complete code walkthrough
Find minimum time for signal propagation
Understanding the problem
Code solution
Time and space analysis
Path reconstruction challenge
Tracking the actual path
Overflow and precision concerns
Adapting Dijkstra for products
Different metrics and objectives
Dijkstra with constraints
Expanded state space
Modified Dijkstra approach
Revisiting nodes in expanded state
Code solution
Key takeaways
Minimax path problem
Maximum edge on path
Modified Dijkstra for minimax
Heap structure for grid
Code solution
When to use minimax Dijkstra
One-time discount optimization
Tracking discount usage
Two-state Dijkstra
Code solution
State expansion patterns
Summary
Dijkstra breaks with negative edges. Bellman-Ford handles them and detects negative cycles. You'll learn when to use each algorithm.
(Why you need it)
(Negative edge problem)
(Core building block)
(Relax all edges repeatedly)
(Maximum path length)
(The algorithm)
(Why it's slower)
(The $n$-th iteration)
(Reachability from cycle)
(CSES 1673)
(Maximum becomes minimum)
(In the original graph)
(Cycle must matter)
(Step-by-step approach)
(Pseudocode walkthrough)
(Trace execution)
(summary)
(CSES 1197)
(Reconstructing the cycle)
(Inside the cycle)
(Detection and extraction)
(Pseudocode walkthrough)
(Trace execution)
(summary)
(LeetCode 787)
(Limiting path length)
(Why two arrays matter)
(Modified Bellman-Ford)
(Pseudocode walkthrough)
(Trace execution)
(summary)
(Queue-based relaxation)
(Queue-based approach)
(Counting relaxations)
(Dijkstra vs Bellman-Ford)
(Detecting profit cycles)
(Handling link costs)
(What can go wrong)
(Algorithm characteristics)
(What to avoid)
(How to internalize this)
(What you learned)
You've learned BFS, Dijkstra, Bellman-Ford, and Floyd-Warshall. Now practice mixing them together.
(Choosing the right algorithm)
(Four questions to ask)
(Knowledge check)
(Unweighted graphs only)
(Non-negative weights)
(Common mistakes)
(Negative weights allowed)
(Not always infinite)
(Reachability matters)
(All-pairs, small graphs)
(CSES - Dijkstra)
(Single-source, non-negative)
(Priority queue tricks)
(Why mark visited?)
(C++ code)
(CSES - Bellman-Ford trap)
(Negate and minimize)
(Not all cycles matter)
(Reachability check)
(Bellman-Ford + BFS)
(CSES - State-space Dijkstra)
(Tracking coupon usage)
(Two types of edges)
(Complexity check)
(State Dijkstra)
(CSES - Dijkstra + counting)
(Four arrays)
(When relaxing u→v)
(Equality case)
(Extended Dijkstra)
Codeforces 295B - Reverse F...
(Process deletions backward)
(Adding one node at a time)
(Why reverse works)
(Reverse Floyd-Warshall)
(What you practiced)
Union by rank/size, path compression, rollback DSU, and applications.
Dynamic changes
The Structure
Who is the boss?
Tracking relationships
Finding the Leader
Merging Groups
Long Chains
The Magic Step
Coding the Magic
Balancing the Tree
Coding the Merger
Copy-Paste Ready
Application 1
LeetCode 684
First Hit
Application 2
LeetCode 547 (DSU Version)
Iterating the Matrix
Application 3
CSES Problem Set
Maintaining State
Symbols as Nodes
LeetCode 990
Two Passes
Swapping Logic
LeetCode 1202
Sorting Components
Mapping Data
LeetCode 721
Emails are Edges
Connecting pixels
LeetCode 827
DSU + Virtual Flip
Reducing Edges
Codeforces 1263D
Letters are Hubs
Reordering Time
LeetCode 1697
Sorting Everything
Destruction is hard
USACO Gold
Adding Barns
Dynamic Connectivity
Spanning trees connect all nodes with minimum edges. Learn Kruskal's and Prim's algorithms.
(Why we need MSTs)
(Definition and properties)
(Minimum total edge weight)
Foundation for MST algos
(Avoiding unnecessary edges)
(Sort edges, add greedily)
(Detecting cycles efficiently)
(Sorting dominates)
(Step-by-step implementation)
(Grow tree from one node)
(Finding lightest edge fast)
(Heap operations dominate)
(Step-by-step implementation)
(Choosing the right algorithm)
(Handling multiple components)
CSES 1675 - MST or impossible
(CSES 1675)
(MST needs connected graph)
(Sort edges, union components)
(Count edges added)
(Kruskal with edge count)
(CSES 1675)
(Example execution)
(When MST doesn't exist)
LeetCode 1584 - Complete gr...
(LeetCode 1584)
(n² edges to consider)
(Computing edge weights)
(Compute edges as needed)
(Prim with lazy heap)
(LeetCode 1584)
(Example execution)
(Implicit vs explicit graphs)
CSES 1666 - MSF for components
(CSES 1666)
(DSU or DFS)
(Chain them together)
(DSU then connect)
(DSU and component list)
(CSES 1666)
(Example execution)
(MST ideas without weights)
(When is MST unique?)
(Almost minimum spanning tree)
(Real-world applications)
(MST properties quiz)
(Algorithm selection quiz)
(What you learned)
Kahn's algorithm (BFS-based), DFS-based topological sort, and cycle detection in directed graphs.
Getting Dressed
No Circles Allowed
Peeling the Onion
The Template
The Leftovers
LeetCode 210
Building dependencies
In-degree tracks readiness
Kahn's step by step
The code
What you learned
Alternative to Kahn
When to use each
Pitfalls to avoid
Controlling the Choice
Is there only one way?
Deriving Edges
The Real Power
The code
DP on topological order
Kahn's + DP
CSES 1680
Safety
DAG DP pattern
CSES 1681
Summing paths instead of max
Topological order guarantees
The code
Counting on DAGs
LeetCode 2050
Finish time propagates
DP on topological order
The code
Critical Path Method
Order from Chaos
Shortest/longest path in DAGs, counting paths, and DP with topological order.
The Goal
No cycles = DP works
Linear ordering of nodes
Process in topological order
Knowledge check
Better than Dijkstra
What dp[u] means
Step by step process
Walking through an instance
Flip the minimization
Scheduling and critical paths
Knowledge check
CSES 1680
Edge weights are 1
Networks can have cycles
dp[u] = max cities to u
Backtracking from destination
Complete solution
Handling IMPOSSIBLE
Step by step trace
summary
How many ways to reach
CSES 1681
dp[u] = number of paths to u
Paths are independent
Output modulo 10^9+7
Complete solution
Tracing the DP
Knowledge check
Base case matters
Apply after every operation
Initialize multiple base cases
Sum over all endpoints
Reverse edges for DP
Paths through a node
Knowledge check
CSES 1673
Infinite score problem
Negate for maximization
Reachable from 1 and reaches n
Complete solution
Cycles break the pattern
Trees are DAGs
Updating distance estimates
Linear ordering of DAG nodes
LeetCode 210
LeetCode 787 with constraint
Problem recognition
State space graphs
What we learned
You've learned BFS, DFS, cycle detection, and DP on DAGs. Now you choose which technique to use for each problem.
Pattern recognition
(When to use each technique)
(Identify the right technique)
(BFS vs DFS comparison)
(CSES shortest path)
(Pause before pattern reveal)
(Choose the technique)
(BFS with path reconstruction)
(CSES maze escape)
(Why not DFS)
(Grid shortest path)
(BFS on grid)
(LeetCode 207 prerequisites)
(Detecting impossibility)
(Cycle detection problem)
(Cycle detection via DFS)
CSES undirected cycle
Undirected vs directed
(Undirected cycle detection)
(DFS with parent tracking)
(CSES multi-source BFS)
(Multiple sources)
(Multi-source BFS)
(Two-phase BFS)
(CSES longest path in DAG)
(Longest path technique)
(DP vs BFS)
DP on DAG with paths
(Mixed pattern review)
(BFS variations)
(When to use DP on DAG)
(Quick reference guide)
(What to avoid)
(What comes after)
(Pattern recognition proficiency)
Mutual reachability in directed graphs. Kosaraju and Tarjan algorithms. The condensation DAG.
(Why this section matters)
(Mutual reachability)
(Compression and structure)
(Two DFS passes)
(Implementation outline)
(4-node directed graph)
(C++ code)
(Single DFS with low-link)
(Discovery and low-link)
(Same 4-node graph)
(C++ code)
(When to use which)
(DAG of SCCs)
(Implementation)
Package managers, build sys...
(Boolean satisfiability)
(CSES 1683 intro)
(SCC detection)
(C++ code)
(CSES 1686 intro)
(SCC + DAG DP)
(C++ code)
(CSES 1682 intro)
(SCC count)
(C++ code)
(Self-loops and single nodes)
(Debugging tips)
(Why it doesn't apply)
(Problem recognition)
(SCC detection)
(Condensation graph DP)
(Reachability check)
(Different concepts)
(Web, social, citation)
(Both algorithms)
(Memory usage)
(Finding directed cycles)
(No direct connection)
(Code references)
(What you learned)
Converting logic constraints into implication graphs. Using SCCs to determine satisfiability and construct valid assignments.
(Logic meets graphs)
(Boolean satisfiability)
(Exactly two variables)
(True or false)
(Clauses become edges)
(The core transformation)
(Logic equivalence)
(Building the graph)
(Satisfiability condition)
(Contradiction proof)
(Using SCC order)
Avoiding forced contradictions
(Four steps)
(Linear time)
(Read statement)
(Toppings as variables)
(Converting constraints)
(SCC test)
(SCC topological order)
(C++ solution)
(Simplest satisfiability)
(Same topping opposite signs)
(Recognition and modeling)
(Mutual exclusion)
(One must be true)
(Implication directly)
(Combining constraints)
(Time slot assignment)
(Binary time slots)
(SCC assignment)
(Binary choices)
(Problem recognition)
(Harder problems)
(Avoiding pitfalls)
(Finding errors)
(OR of literals)
(Variable or negation)
(Valid assignment exists)
(If-then statement)
(CSES - Giant Pizza)
(Graph coloring variant)
(Time slot assignment)
(Drawing the graph)
(Graph algorithms unite)
(What you learned)
Mixed Practice: Connectivity & MST
Why mix connectivity patterns
How to pick the right techn...
When to use each
Different use cases
Test connectivity pattern r...
Recognize SCC pattern
CSES - DSU application
Dynamic connectivity pattern
DSU with component tracking
Track connected components
CSES - MST basic
Minimum cost spanning
Kruskal's algorithm
How many edges in MST
CSES - SCC verification
Bidirectional reachability ...
Kosaraju with example output
When is graph strongly conn...
LeetCode 1192 - Finding bri...
Critical edge identification
Tarjan bridge algorithm
When is edge a bridge
Codeforces 427C - SCC optimize
Compress to DAG
SCC + cost minimization
When to compress graph
Codeforces 160D - MST edge ...
Three categories
MST + bridge detection
When edge appears in every MST
How to approach mixed problems
Techniques used together
Which techniques combine
Where to go from here
Connectivity pattern summary
You know tree DP for one root. Learn to compute answers for all roots in linear time.
(Why rerooting matters)
(The $O(n^2)$ problem)
(Incremental updates)
(The core algorithm)
(Subtree DP)
(Parent contributions)
(Merging results)
(Child contribution logic)
(Efficient sibling exclusion)
(Apply to any problem)
(CSES problem)
(Distance shift insight)
(Subtree sums)
(Outside contributions)
(Merge down and up)
(C++ code)
(4-node tree)
(Distance aggregation)
(LeetCode variant)
(0-indexed implementation)
O(n) proof
($n$ times faster)
(All-roots signal)
(DP state choice)
(Sibling combination)
(Maximum problems)
(Distance histograms)
(n=1 and n=2)
(Double-counting)
(3-pass extensions)
(Solve 5 problems)
Testing rerooting
(Key formula recall)
(Pattern recognition)
(Exclude child correctly)
(For each node signal)
(Tuple states)
(Rare dynamic case)
(Two-pass proficiency)
Flatten trees into arrays. Subtrees become ranges. Query and update subtrees with range structures.
(Converting trees to arrays)
(DFS traversal order)
(tin and tout arrays)
(Why this works)
(Building the array)
(Computing tin and tout)
(Computing times step by step)
(Entry/exit time properties)
(CSES 1137)
(The key observation)
(Entry times only)
(Euler tour plus segment tree)
(Code and submit)
(Example execution)
(summary)
(Different approaches)
(Just tin values)
(tin and tout pairs)
(Complete node sequence)
(Variant selection)
(CSES 1138)
(DFS order property)
(Converting to range query)
(Modified Euler tour)
(BIT for prefix sums)
(Example execution)
Adding and subtracting
(Beyond sums)
(When to use Fenwick tree)
(Memory usage)
(Point vs range updates)
(What you can ask)
(Fast relationship test)
(Fixed root only)
(Complexity analysis)
(Consistent traversal)
Different tools, same goal
(Implementation advice)
(What goes wrong)
(CSES 1688)
(RMQ on depth array)
(Full tour plus RMQ)
(Submit your code)
(Full tour power)
(What you learned)
Pattern recognition practice. Decision trees for choosing the right technique. Six problems spanning all tree fundamentals.
(Pattern recognition practice)
(Simple traversal vs DP)
(One root vs all roots)
(Knowledge check)
(CSES - Subtree size)
(Pause before reading)
(Choose the approach)
(C++ code)
(CSES - Longest path)
(Two approaches exist)
(Two methods)
(DP approach)
(CSES - Max matching)
(State definition)
(DP definition)
(Subtree DP with states)
(CSES - Sum of distances)
(Rerooting pattern)
(Moving the root)
(Rerooting DP)
(CF 219D - Directed edges)
(Directed rerooting)
(Cost change)
(Rerooting with directions)
(CF 1324F - Forces rerooting)
(Subtree + rerooting)
(Answer structure)
(Rerooting with max)
(Pattern recognition summary)
Find ancestors by jumping one step at a time? That's O(n). Binary lifting makes it O(log n).
(The goal)
(Find ancestor k steps up)
(Jump one step at a time)
(Any number as sum of powers)
(Store power-of-2 ancestors)
(How many columns needed)
(Direct parents)
Build from previous
(How $up[v][2]$ is computed)
(Column by column)
(Pseudocode for preprocessing)
(Decompose k into powers)
(Jump by set bits)
(Finding 13th ancestor)
(Preprocessing and queries)
(CSES 1687 - k-th ancestor)
(Input is a tree)
(When k exceeds depth)
Preprocess then query
Binary lifting code
(Sample input trace)
(What you practiced)
Finding LCA
(CSES 1688 - LCA)
(Bring nodes to same level)
(Jump both simultaneously)
(Jump as far as possible)
(LCA with binary lifting)
(Pseudocode for LCA)
(Sample LCA trace)
(Nodes in separate branches)
(What you practiced)
(LeetCode 1483)
(Build table once)
(Return -1 if out of bounds)
(Class-based binary lifting)
(Pseudocode for class)
(Sample queries)
(What you practiced)
(Where binary lifting is used)
(Reducing memory usage)
(Why binary lifting wins)
(More LCA techniques)
(What you learned)
You've learned binary lifting. Now find the lowest common ancestor of two nodes efficiently.
Finding ancestors fast
(Nearest shared ancestor)
(Distance and path queries)
(Climb to same depth)
(Climbing step by step)
(Jump in powers of two)
(Building the up table)
(Finding the split point)
(Find the meeting point)
(Preprocessing and query time)
(LeetCode 236)
(LeetCode 236)
(enabling array algorithms)
(Null and target nodes)
Combine left and right results
(Pseudocode)
(LeetCode 236)
(Tracing the recursion)
(Bottom-up propagation)
(Convert tree to array)
(DFS with recording)
(Minimum depth in range)
(Precompute range minimums)
(Dynamic programming)
(Overlapping ranges trick)
(Combining both techniques)
(Time and space analysis)
(Using LCA)
(CSES 1135)
(CSES 1135)
(Setup for fast queries)
(Pseudocode)
(CSES 1135)
(Pay once, query many)
(CSES 1136)
(CSES 1136)
Add to endpoints, subtract ...
(Sum children contributions)
(Mark and propagate)
(Pseudocode)
(CSES 1136)
(Tracing the algorithm)
(Fixing the formula)
(Efficient path updates)
(Maximum, minimum, sum)
(Carrying extra data)
(Distance formula)
(When to use each)
(Pitfalls to avoid)
(Beyond basic LCA)
(What you learned)
Two-player games where positions are graph nodes. You analyze winning strategies using backward induction.
(The goal)
(Every pair distance)
(The simple solution)
(DP on intermediate nodes)
(dp[k][i][j] meaning)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(O(V³) analysis)
(Floyd-Warshall concept)
(Detection method)
(Building actual paths)
(Reachability variant)
(Algorithm comparison)
(Practice problem)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(Code walkthrough)
(Step-by-step example)
(CSES 1672)
(Practice problem)
(Practice problem)
(Floyd-Warshall concept)
(Code walkthrough)
(Step-by-step example)
(Code walkthrough)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(Floyd-Warshall concept)
(Practice problem)
(What you learned)
Alternating maximization an...
(Skipping irrelevant branches)
(Avoiding recomputation)
(Introduction)
(Minimax on tree structure)
(Implementation)
(What you learned)
(Games that never end)
Identifying non-terminating...
(Player positions alternate)
(Game-playing algorithms)
(Attacker vs defender games)
Path planning with adversaries
(Adding randomness to games)
(Runtime considerations)
(Problem recognition patterns)
(What to avoid)
(Verification strategies)
(Beyond basic games)
(What you learned)
You know Euler tours for subtrees. HLD handles path queries by decomposing into heavy chains.
(Solving path queries fast)
(Maximum on a path)
Paths cross subtree boundaries
(Break paths into chains)
(Counting descendants)
(Splitting by subtree size)
(Maximal heavy sequences)
(Why paths cross few chains)
(Two paths meet at ancestor)
(Assigning nodes to chains)
(Indexing nodes within chains)
(Top node of each chain)
(Range queries on chains)
(Flatten all chains)
(Walk up to LCA)
(Comparing node depths)
(Jumping to parent)
(Changing a node value)
(Where to store values)
(Finding the meeting point)
(Time and space bounds)
(Computing sizes and parents)
(Building chains)
(Supporting range max)
(Combining chain segments)
(Modifying all nodes on path)
(Sum instead of maximum)
(CSES 1138 path maximum)
(Decompose the tree)
(Store values by position)
(Walk up both sides)
(Change one node)
(Per-query analysis)
(Pseudocode)
(What you learned)
(SPOJ classic HLD problem)
(Store edge weights at nodes)
(Exclude the LCA)
Change edge $i$ to weight $ti$
(Same as vertex version)
(Edge indexing)
(Edge queries via HLD)
(Path queries on trees)
(Updates vs queries)
(Pitfalls to avoid)
(Testing your understanding)
(Testing your understanding)
(Testing your understanding)
(What you learned)
Some distance problems resist DFS and DP. Centroid decomposition gives divide-and-conquer on trees.
(Divide and conquer on trees)
(When DFS and DP fail)
(The balance point of a tree)
(Every tree has one)
(Walk toward heavy subtrees)
(Walking through the process)
Why it works for divide-and...
Recursive structure of cent...
(Each level halves the size)
(Recursive centroid finding)
(Two different structures)
core idea for path problems
(The general pattern)
(CSES 2079)
(Problem link)
(Compute sizes with DFS)
(Move toward balance)
(Two-phase approach)
(Complete solution)
(Tracing the algorithm)
(summary)
(CSES 2080)
(Problem link)
(Divide by centroid)
Count distances from centroid
Avoid counting paths within...
(The recursive structure)
(Complete solution)
(Example trace)
(Path counting with centroids)
(CSES 2081)
(Problem link)
(Modify the counting step)
(Range query on distances)
(Range counting with map)
(Example with range)
(Range queries on paths)
Preprocessing for fast queries
(Problem recognition)
(Choosing the right tool)
(Avoiding common mistakes)
(Why it's O(n log n))
(Memory usage)
(Beyond basic path counting)
(Common errors and fixes)
(Build your skills)
(Centroid definition)
(Decomposition depth)
(Path counting logic)
(What you learned)
You know how to process subtrees. Now merge results from children using small-to-large merging.
(The merging problem)
(Combining child results)
(Why it fails)
(O(n²) disaster)
(Merge small into large)
(Doubling argument)
(DSU on tree structure)
(High-level template)
(First DFS pass)
(Memory optimization)
(CSES 1139)
(Why it times out)
(Small-to-large merging)
(C++ with sets)
(Example execution)
(What you learned)
(Codeforces 600E)
(Frequency tracking)
(Small-to-large on maps)
(Tracking maximum frequency)
(C++ with maps)
(Example execution)
(What you learned)
(Pattern recognition)
(Other techniques)
(Space complexity)
(Heavy child concept)
(Avoiding bugs)
(Common mistakes)
(Complexity verification)
(Pattern recognition)
(Beyond basic merging)
(Building intuition)
(What to expect)
(Query handling)
(Reducing memory usage)
(Practical performance)
(Advanced applications)
(DSU on tree origin)
(What you learned)
What if every node has exactly one outgoing edge? These functional graphs have special structure.
(The special constraint)
(Successor as a function)
(Why cycles always appear)
(Visualizing the structure)
(The power of predictability)
(Tortoise and hare)
(The detection phase)
(The meeting point trick)
(The distance proof)
(Measuring the loop)
(LeetCode 142)
(Detection then location)
(Handling no cycle case)
(Floyd's algorithm in code)
(Example execution)
(summary)
(Jumping in powers of 2)
(Computing jump pointers)
(Decomposing k into powers)
(CSES 1750)
(Amortizing the cost)
(Why powers of 2 work)
(Binary lifting in code)
(Example execution)
(summary)
(Finding path length)
(Two regions)
(One-pass detection)
(Four scenarios)
(CSES 1160)
(Marking the loop)
(Tail length computation)
(Tracking location in loop)
(Example execution)
(summary)
(CSES 1751)
Computing all distances at ...
(Tracking DFS state)
(Example execution)
(summary)
(Application to permutations)
(Breaking into components)
(Minimum swaps to sort)
(Elimination sequences)
(Reducing memory usage)
(What goes wrong)
(What you learned)
Mixed Practice: Advanced Tree Techniques
Pattern recognition across ...
What the problem statement ...
First decision splits the tree
(Path counting needs centroid)
When subtrees combine their...
(CSES Tree, LCA application)
(Before jumping to code)
(Which technique fits best)
(Why LCA is the right choice)
(Binary lifting LCA code)
(Pattern recognition takeaway)
CSES Tree, path max with up...
(Updates change everything)
(Path queries plus updates)
(Why HLD handles updates)
(HLD with segment trees)
(When to use HLD)
Codeforces 208E, LCA + Eule...
(Combining two techniques)
(Multiple techniques combined)
(Two techniques work together)
LCA to find ancestor, Euler...
(Combining techniques)
Codeforces 600E, Small-to-L...
Merging subtree frequency c...
(Avoiding quadratic merging)
(Why Small-to-Large works)
DFS with Small-to-Large mer...
(When to merge small-to-large)
(CSES, centroid decomposition)
(Counting paths by length)
(Path counting technique)
(Why centroid splits the tree)
Centroid recursion with dis...
When to use centroid decomp
(Pattern recognition summary)
(Critical edges and vertices)
Finding weak spots in networks
Edge whose removal disconnects
(Visualizing critical edges)
Network reliability applica...
Vertex whose removal discon...
Visualizing critical vertices
Foundation for Tarjan's algo
(Tree edges vs back edges)
Cycles provide alternate paths
(When DFS first visits vertex)
(Earliest reachable ancestor)
(Can you escape the subtree?)
Computing values step by step
(One-pass DFS solution)
(When is an edge a bridge?)
(DFS with discovery and low)
(Step-by-step execution)
(Finding critical vertices)
(Root with multiple children)
(Child cannot bypass parent)
(DFS with discovery and low)
(Step-by-step execution)
(Bridge in network graph)
(LeetCode 1192)
(Visualizing the network)
Apply Tarjan's bridge algo
(Tarjan's bridge detection)
(Python with DFS)
(Running Tarjan's algorithm)
(Linear in edges)
(Single edge and cycles)
(What you learned)
(Maximal set without bridges)
(Contract non-bridge edges)
(Visualizing the structure)
(Critical vertices in network)
(Graph with critical vertices)
Apply Tarjan's vertex algo
(DFS-based detection)
(Python with DFS)
(Step-by-step execution)
(Linear in edges)
Single vertex and complete ...
(What you learned)
Identifying single points o...
Dividing graphs at weak points
(Fault tolerance in circuits)
Maximal subgraph without ar...
(Using edge stack during DFS)
Condensing 2-edge-connected...
(Condensing a graph)
(What you learned)
A whole class you haven't touched: flow networks. Learn Ford-Fulkerson and maximum flow.
(Why flow matters)
Directed graph with capacities
(How much flow on each edge)
(Simple network walkthrough)
(Find maximum throughput)
(Captures remaining capacity)
(Path that increases flow)
Iterative augmentation fram...
(Correctness argument)
BFS for shortest augmenting...
(BFS-based max flow)
(Forward and backward edges)
Adjacency list with capacities
(Edmonds-Karp analysis)
(CSES 1694)
(Direct translation to flow)
(Edmonds-Karp code)
(Example with 4 nodes)
(No path, single edge)
(Partitioning the graph)
(Cut with minimum capacity)
(Duality result)
Run BFS on final residual g...
(CSES 1695)
Unit capacities mean edge-d...
(BFS on residual graph)
Edmonds-Karp + cut extraction
(Example with 4 cities)
(Classic flow application)
(CSES 1696)
(Source and sink setup)
(Check flow on middle edges)
(Bipartite matching via flow)
(Example with 3 boys, 2 girls)
(Unbalanced sides, no edges)
Reduction to single source/...
(Split nodes into in/out)
Forcing minimum flow on edges
Integral capacities yield i...
(Counting independent routes)
(Recognizing flow problems)
(What to avoid)
(Beyond Edmonds-Karp)
(Real-world applications)
(Path that increases flow)
Remaining capacities after ...
Partition separating source...
(How to get good at flow)
(What you learned)
Two groups where members can connect across groups. Find the maximum number of matched pairs.
(Pairing people and tasks)
(No shared endpoints)
(Largest possible set)
(Everyone gets paired)
Alternating matched and unm...
(One more edge each time)
(DFS from unmatched nodes)
Greedy augmenting path search
(Try to match left node)
(CSES 1696)
(CSES link)
(Bipartite matching directly)
(DFS-based matching)
(C++ Kuhn's algorithm)
(3 boys 4 girls)
(Direct bipartite matching)
(Flow network construction)
(Flow equals matching)
(Matching equals vertex cover)
(Construction from matching)
Condition for perfect matching
(Exponential subsets)
(Workers and tasks)
(Time slots and tasks)
(General bipartite graph)
(Kuhn's algorithm directly)
(Python version)
(4 left 3 right)
(Recursive rematching)
(Greedy vs matching)
(Two pointers)
(Bipartite matching approach)
(Greedy two pointers)
(When to use matching)
(Maximum weight matching)
(Nodes arrive over time)
Matching impl errors
(Stop when matching is full)
(Faster maximum matching)
Kuhn vs Max Flow vs Hopcrof...
(König's theorem application)
(Cover with edges)
(Complement of vertex cover)
(When to use)
(Maximum matching algorithms)
You've mastered max flow. Now learn minimum cuts: the cheapest way to disconnect source from sink.
(Splitting networks)
(Partitioning vertices)
(Sum of crossing edges)
(Source and sink separation)
(Cheapest way to disconnect)
(Flow equals cut capacity)
(Why flow equals cut)
Using max flow residual graph
(Step by step)
(No augmenting paths left)
(Small network)
(No source or sink)
(Finding global min cut)
(Minimum edges to disconnect)
Minimum vertices to disconnect
(Finding weak points)
(Foreground and background)
(Splitting data into groups)
(CSES 1695)
(CSES 1695)
(Flow equals number of roads)
(Which roads to block)
(Each road becomes two edges)
(Pseudocode)
(CSES 1695)
(Real-world uses)
(CSES 1711)
(CSES 1711)
(Edge-disjoint paths)
(Extracting paths from flow)
(Trace and subtract)
(Pseudocode)
(CSES 1711)
(Paths from flow)
(Custom problem)
(Brute force approach)
(Contracting vertices)
(Picking vertices to cut)
(Step by step)
(Pseudocode for Stoer-Wagner)
(Different problem types)
(What you learned)
Visit every edge exactly once. Learn when Eulerian paths exist and how to find them.
What you'll learn about Euler paths.
Definition and examples.
Euler path that returns to start.
When Euler paths exist in undirected graphs.
When Euler paths exist in directed graphs.
Algorithm to verify conditions.
The standard algorithm for Euler paths.
Step-by-step implementation.
Intuition behind the algorithm.
Efficiency analysis.
CSES 1691 - Find Euler circuit.
Check degrees and connectivity.
Apply Hierholzer from vertex 1.
Code walkthrough.
What you learned from this problem.
CSES 1693 - Directed Euler path.
Check in/out degree conditions.
Code walkthrough.
Directed vs undirected differences.
LeetCode 332 - Lexicographically smallest path.
Sort and use Hierholzer.
Code walkthrough.
Visiting all n-bit strings.
CSES 1692 - Construct the sequence.
Build De Bruijn graph and find Euler circuit.
Code walkthrough.
LeetCode 753 - De Bruijn application.
Generalized De Bruijn graph.
When graph isn't Eulerian.
Where Euler paths appear.
Pitfalls to avoid.
Summary of Euler paths and circuits.
Test your ability to recognize which graph algorithm to apply. Problems spanning flow, matching, SCCs, and more.
What this practice section covers.
How to choose the right algorithm.
When to use strongly connected components.
When to use 2-SAT.
When each node has exactly one outgoing edge.
Visiting vertices vs visiting edges.
CSES 1686 - SCC and DP.
Recognizing the SCC pattern.
Code walkthrough.
CSES 1684 - 2-SAT.
Recognizing the 2-SAT pattern.
Code walkthrough.
CSES 1160 - Functional graphs.
Recognizing the functional graph pattern.
High-level approach.
CSES 1690 - Bitmask DP.
Recognizing the bitmask DP pattern.
Code walkthrough.
CSES 1689 - Backtracking.
Backtracking with heuristics.
Code walkthrough.
Test your ability to identify algorithms.
Pitfalls in pattern recognition.
Summary of pattern recognition.