Interactive visualizers

138 pages, one house style. Every diagram is driven by a real, instrumented implementation of the algorithm it’s showing — step through with the controls or the arrow keys, and the code pane highlights the exact line running at each frame.

← Study library·Pattern 1 — Traversal·Pattern 2 — Tree Recursion·3 — Two Pointers·4 — Sliding Window·5 — Binary Search·6 — Graphs

Pattern 1 — Traversal

Order of visitation is the whole subject: what you see, when you see it, and what you are allowed to remember. Twenty-two pages.

Depth-first traversals, compared

Recursive vs. Iterative — all eight waysEasypreorder, inorder & postorder × 2, plus 3 postorder tricks

A Traversal fundamentals

102Binary Tree Level Order TraversalMediumBFS & DFS, side by side 94Binary Tree Inorder TraversalEasyMorris threading, O(1) space 173Binary Search Tree IteratorMediumcontrolled recursion

B The level-order family

199Binary Tree Right Side ViewMediumlast node per level 103Zigzag Level Order TraversalMediumreverse alternate levels 662Maximum Width of Binary TreeMediumnull gaps count too 987Vertical Order TraversalHardrow, col, then value 111Minimum Depth of Binary TreeEasyBFS stops at the first leaf Level-Order Accumulators, ComparedMedium107, 637, 515 & 1161 — one BFS, four accumulators

C The tree as a graph

863All Nodes Distance K in Binary TreeMediumparent map + graph BFS 2385Amount of Time for Binary Tree to Be InfectedMediumBFS from patient zero

D N-ary generalizations

429N-ary Tree Level Order TraversalMediumany number of children 559Maximum Depth of N-ary TreeEasymax over children 589N-ary Tree Preorder TraversalEasywhy children are pushed in reverse 590N-ary Tree Postorder TraversalEasyrecursion, and the reverse-preorder trick

E Traversal without a tree

331Verify Preorder SerializationMediumslot counting — no tree is ever built

Extra reps

993Cousins in Binary TreeEasydepth and parent in one pass 1302Deepest Leaves SumMediumlet the last level win 623Add One Row to TreeMediumthe tree is redrawn as it grows 1609Even Odd TreeMediumparity and direction, per level 671Second Minimum NodeEasythe prune that skips whole subtrees

Pattern 2 — Tree Recursion

One skeleton — ask both children, combine, hand the result up — and twelve mutations of it. What changes between sub-variants is never the traversal; it is what travels, and in which direction. All 30 pages, grouped as in the bundle.

A Postorder aggregationidentity · combine · own contribution

404Sum of Left LeavesEasythe parent knows which child it is 104Maximum Depth of Binary TreeEasythe atom — 1 + max(L, R) 110Balanced Binary TreeEasy−1 as a sentinel abort 222Count Complete Tree Nodes⚠ Trapthe shape is the algorithm

B Two trees in lockstepthe pairing rule is a parameter

617Merge Two Binary TreesEasythe pairing rule when either side may be null 951Flip Equivalent Binary TreesMediummatch children in either order 100Same TreeEasythe three base cases, in order 101Symmetric TreeEasythe same machine, crossed 572Subtree of Another TreeEasya traversal inside a traversal

C The record / return splitreturn what composes, record what does not

687Longest Univalue PathMediumreturn the one-sided arm, record the join 543Diameter of Binary Tree⚠ Trapthe proof problem of the pattern 124Binary Tree Maximum Path SumHardthe clamp is the difficulty

D State flowing downthe parameter is the state

1448Count Good Nodes in Binary TreeMediummaxSoFar down, a count up 129Sum Root to Leaf NumbersMediumcur × 10 + val, harvested at leaves

E Root-to-leaf pathsadd before recursing, remove after

112Path SumEasynull is not a leaf 257Binary Tree PathsEasythe remove is the sub-variant 113Path Sum IIMediumcopy on record, or return N empty lists

F Prefix sums on the root paththe bridge from arrays to trees

437Path Sum IIIMediumLC 560's hash map, undone on the way up

G Lowest common ancestoran overloaded return value

236Lowest Common Ancestor of a Binary TreeMediumboth sides report → split point 1123LCA of Deepest LeavesMedium(depth, node) upward — a tie wins

H Construction from traversalsit is always an off-by-one

105Construct from Preorder + InorderMediumpreorder names, inorder sizes 106Construct from Inorder + PostorderMediumright subtree built first

I Serializationthe null markers are the structure

297Serialize and Deserialize Binary TreeHardone shared cursor, never an index copy

J Structural rewiringonce you mutate, order is load-bearing

226Invert Binary TreeEasyrecurse, then rewire 114Flatten Binary Tree to Linked ListMediumbuild the chain backwards — plus Morris 117Populating Next Right Pointers IIMediumthe linked level is the queue

K Multi-dimensional statereturn every case the parent might be in

337House Robber IIIMedium(rob, skip) — the model for the rest 979Distribute Coins in Binary TreeMediuma signed surplus; count flow, not nodes 968Binary Tree CamerasHardthree states, placed as late as possible

L Rerooting — two passeswhen every node needs its own answer

834Sum of Distances in TreeHardmeasure up, then reroot down in O(1)

Pattern 3 — Two Pointers

Two indices, and an argument for why moving one of them can never skip the answer. 33 pages.

A Converging pointers on sorted datathe discard argument is the whole pattern

167Two Sum II — Sorted ArrayEasySorted input turns the hash map into two indices… 1099Two Sum Less Than KEasyNo early exit here — every sum under k is a candidate, not… 125Valid PalindromeEasySkip non-alphanumeric characters, compare… 977Squares of a Sorted ArrayEasyNegatives square into big positives — the largest square… 680Valid Palindrome IIEasyOn a mismatch, fork: try skipping left, then try skipping… 344Reverse StringEasyIn-place swap, inward — the textbook two-pointer warm-up. 345Reverse Vowels of a StringEasySame inward swap as Reverse String, but skip past…

B Converging with a discard proofgreedy: prove the smaller side can be dropped

11Container With Most WaterMediumAlways move the shorter wall — moving the taller one can… 42Trapping Rain WaterHardThe smaller wall’s water level is always fully determined…

C k-Sum reductionpeel an index, recurse, bottom out at two pointers

153SumMediumSort, fix i, then slide left/right inward — with two… 163Sum ClosestMediumTrack whichever sum has landed nearest the target — an… 184SumMedium3Sum with one more nested fixed pointer — and one more… 2593Sum SmallerMediumCount, don’t collect — one valid pair means every value… Generalized kSumMedium2Sum, 3Sum, 4Sum are one recursive pattern — fix pointers…

D Read/write compactionthe prefix [0, write) is the answer so far

27Remove ElementEasythe write head keeps only what survives 26Remove Duplicates from Sorted ArrayEasycompare against the last kept, not the last seen 80Remove Duplicates from Sorted Array IIMediumthe write−2 lookback, and how it generalises to k

E Two-sequence advancethe whole design question is which pointer moves

392Is SubsequenceEasyonly i advances on a match 986Interval List IntersectionsMediumretire whichever interval ends first 844Backspace String CompareEasyscan right to left with a skip counter

F Backward-writing mergewrite from the back and you never clobber

88Merge Sorted ArrayEasyw = i + j + 1 is the proof it is safe

G Fast & slow, and gap pointersdistance, not position

141Linked List CycleEasyFast runs out of road exactly when slow lands on the middle. 876Middle of the Linked ListEasy 19Remove Nth Node From EndMediumA dummy node and an n-node gap turn removal into one pass. 142Linked List Cycle IIMediumphase two finds the entrance 287Find the Duplicate NumberMediumthe array is secretly a linked list

H Partitioningthree regions, one pass

75Sort ColorsMediumThree pointers, one pass — low / mid / high carve out… 215Kth Largest Element in an ArrayMediumquickselect — recurse into one side only

I Expand around center2n−1 centers, not n

5Longest Palindromic SubstringMediumkeep the best span 647Palindromic SubstringsMediumsame loop, count instead of max

J Cyclic sortvalue v belongs at index v−1

448Find All Numbers Disappeared in an ArrayEasyswap each value home, then read the gaps 41First Missing PositiveHardthe while-swap duplicate guard is the hard line

K Counting pairs on sorted datacount the block, don't enumerate it

611Valid Triangle NumberMediumFix the largest side; one valid pair means every value…

Pattern 4 — Sliding Window

One pass, two boundaries, and an invariant that decides when the window has to give ground. 27 pages.

A Fixed-size windowthe frame never changes size

643Maximum Average Subarray IEasyBuild the first window once, then slide — track the max… 2841Maximum Sum of Distinct Subarrays With Length KMediumA running sum and a frequency map — the window only counts… 1456Maximum Number of Vowels in a SubstringMediumadd the entering, drop the leaving 1052Grumpy Bookstore OwnerMediumbanked + rescued, as two separate totals 2134Minimum Swaps to Group All 1’s Together IIMediumwidth is derived, and the array is circular

B Variable window, maximize lengthgrow greedily, shrink only when invalid

3Longest Substring Without Repeating CharactersMediumright always moves forward. left only moves when the… 1004Max Consecutive Ones IIIMediumSame shrink-when-forced shape — but a zeroCount replaces… 340Longest Substring with At Most K DistinctMediumdelete the key at count zero 1493Longest Subarray of 1’s After Deleting OneMediumthe −1 you still owe

C Variable window, minimize lengthshrink as far as it will go, then record

76Minimum Window SubstringHardExpand until valid, then contract as far as possible. A… 209Minimum Size Subarray SumMediumrecord inside the shrink loop 1234Replace the Substring for Balanced StringMediumtest the counts outside the window

D Non-shrinking windowsthe window slides but never contracts

424Longest Repeating Character ReplacementMediuma stale maxCount that cannot corrupt the answer

E Frequency-map matchinga matched counter beats rescanning the map

567Permutation in StringMediumA permutation is a rearrangement — so match a fixed window… 438Find All Anagrams in a StringMediumIdentical machinery to Permutation in String — but collect…

F Counting windowsa valid window contributes r − l + 1

713Subarray Product Less Than KMediumevery suffix of the window, banked at once 1358Substrings Containing All Three CharactersMediummin of the three last-occurrences is the boundary

G At-most-K → exactly-Kexactly(k) = atMost(k) − atMost(k−1)

930Binary Subarrays With SumMediumrun the window twice, subtract 992Subarrays with K Different IntegersHardthe flagship of the decomposition 1248Count Number of Nice SubarraysMediummap to parity and it becomes 930

H Complement / inverse windowsthe ends are not a window, but the middle is

1423Maximum Points You Can Obtain from CardsMediumminimise the fixed-width middle you leave 1658Minimum Operations to Reduce X to ZeroMediummaximise the variable-width middle you keep

I Monotonic deque windowsthe front is always the answer

239Sliding Window MaximumHardA decreasing deque of indices — the front is always the… 1438Longest Subarray with Absolute Diff ≤ LimitMediumtwo deques: one for max, one for min

K ⚠ Anti-patterns — when the window is illegaleach page runs the naive window until it visibly fails

862Shortest Subarray with Sum at Least KHardnegatives break it; monotonic deque on prefixes 560Subarray Sum Equals KMediumno monotonicity, so no window at all 395Longest Substring with At Least K RepeatingMediumfix a parameter to restore monotonicity

Pattern 5 — Binary Search

Halve the space each step — on an array, on a rotation, or on the answer itself. Nine pages.

A/B/C Boundaries and the generic predicatelower bound is the one to memorise

704Binary SearchEasyThe template itself — lo/hi converge, mid splits the… 35Search Insert PositionEasySame template — but even a miss has a useful answer: the… 278First Bad VersionEasyNo array at all — just an API call. The invariant is the…

D Rotated sorted arraysprove which half is still sorted

33Search in Rotated Sorted ArrayMediumFigure out which half is sorted first, then check if the… 153Find Minimum in Rotated Sorted ArrayMediumCompare mid against right (not left) — the half containing…

E Unimodal / peakcompare against the neighbour, not a target

162Find Peak ElementMediumNo target, no full sort — just follow the upward slope. A…

G Answer space, minimize the maximumsearch the answer, test with a predicate

875Koko Eating BananasMediumSearch eating speeds directly — feasible(speed) is… 1011Minimum Capacity to Ship Packages Within D DaysMediumSame \u201cminimize the maximum\u201d shape as Koko —…

K Partition binary searchsearch the split, not the value

4Median of Two Sorted ArraysHardBinary search the partition point on the smaller array —…

Pattern 6 — Graphs

The graph is usually implicit — neighbours are computed, never stored — and the only design decisions are what a node is and what you carry. Twelve pages so far, across all three graph patterns.

A Traversal 1.A — flood fill on a grid

733Flood FillEasythe atom — and the guard that stops it running forever when new == old 200Number of IslandsMediumsink as you go, and why the mark comes before the four calls 695Max Area of IslandMediumthe DFS stops returning void — watch 1 + sum flow back up

B Traversal 1.B — boundary seeding, invert the question

130Surrounded RegionsMediumyou cannot mark “enclosed” — mark what escapes and take the complement 1020Number of EnclavesMedium130’s machine with a different last line: count, do not flip 417Pacific Atlantic Water FlowMediumask which cells the ocean can reach uphill — two floods, not mn

C Traversal 1.C — grid BFS, unweighted shortest path

1091Shortest Path in Binary MatrixMediuma level is a distance — and mark-on-pop, run beside it, returns a longer one

D Traversal 1.D — multi-source BFS

994Rotting OrangesMediumevery source in the queue before the first pop, and the counter that means −1

I Traversal 1.I — enumerating paths on a DAG

797All Paths From Source to TargetMediuma visited set here is a bug — watch it delete correct answers

A Ordering 2.A — directed cycle detection, three colours

207Course ScheduleMediumgrey and black are different facts — one visited bit invents cycles

E Ordering 2.E — union-find, the structure itself

684Redundant ConnectionMediumthe parent forest drawn beside the graph — and what dropping union-by-size costs

E Weighted 3.E — Bellman–Ford, and where Dijkstra breaks

787Cheapest Flights Within K StopsMediuma stop budget voids Dijkstra’s finality — watch a sealed city block the legal route

Also in this folder

Earlier or alternate takes on pages that also appear above, kept because they are not duplicates — they use a different explanatory framing. Listed here so nothing in the folder is unreachable.

110Balanced Binary Tree — standaloneAltpredates the 110 page above 222Count Complete Tree Nodes — standaloneAltpredates the 222 page above 662Maximum Width — “Hotel Binaria”Altnarrative framing of the same algorithm 987Vertical Order — “The Treeton Post Office”Altnarrative framing of the same algorithm 104maxDepth — recursion visualizerAltstandalone, predates the 104 page above

Each page is fully self-contained — open any one directly, no shared assets required. Theme (light/dark/auto) and reading progress are per page, stored locally in your browser.