The deliberate progression
The original 25 modules and all 250 kata numbers are retained. Each module builds on state and control-flow decisions practiced earlier.
Module 01. Execution Grammar and State Mutation
Make loop order, branch selection, counters, streaks, boundaries, and commit points automatic.
Begin with execution, not pattern names. These scans teach you to distinguish the incoming value, the state update and the moment an answer becomes valid. Trace every assignment. A running total, a streak and a run encoder use the same loop driver but have different commit and reset rules.
- Running Total
- Running Minimum and Maximum
- Maximum Value and First Index
- Count Positives, Negatives, and Zeros
- First Cumulative Threshold Crossing
- Longest Positive Streak
- Longest Alternating-Parity Streak
- Run-Length Encoding
- Split on Sentinels
- Peak Active Balance
Module 02. Hash Maps, Sets, and Frequency State
Use remembered information about the past to answer the current event in constant expected time.
The first module summarized a prefix with a few numbers. A map or set lets the prefix remember information by value: membership, frequency, identity relationships or a previous occurrence. Before every lookup, decide whether the current element belongs in the stored history yet. That timing separates a valid pair from using one index twice.
- Two-Sum Indices
- First Repeated Value
- Valid Anagram
- First Unique Character
- Group Anagrams
- Most Frequent with Earliest Tie
- Isomorphic Strings
- Multiset Intersection
- Longest Consecutive Sequence
- Count Equal Pairs
Module 03. Sorting and Ordered Scans
Turn global relationships into local comparisons by imposing useful order.
Sorting deliberately changes the order in which evidence arrives. Equal values become neighbors, intervals can be consumed from left to right, and a current frontier can summarize everything already settled. Identify what ordering buys before paying its cost. Keep the input-order tie policy separate from the sorted processing order.
- Merge Two Sorted Arrays
- Deduplicate a Sorted Array
- Three-Way Sort 0/1/2
- Rank Transform
- Merge Overlapping Intervals
- Insert One Interval
- Intersect Two Interval Lists
- Closest Pair to Target
- Minimum-Difference Pairs
- Sort Records by Multiple Keys
Module 04. Two Pointers and In-Place Read/Write State
Use two coordinated frontiers and prove why each pointer movement is safe.
Two boundaries now cooperate within one structure. Sometimes they converge around candidates; sometimes one reads and another writes a compacted prefix. Do not treat these as one interchangeable template. Name the region each pointer owns and prove why moving it cannot destroy an answer or unread input.
- Reverse an Array In Place
- Normalized Palindrome
- Move Zeros Stably
- Remove a Target In Place
- Two Sum in Sorted Array
- Sorted Squares
- Three Sum to Zero
- Container With Most Water
- Trapping Rain Water
- Partition Evens Before Odds
Module 05. Sliding Windows
Make fixed windows, longest-valid windows, shortest-satisfying windows, and counting windows feel distinct.
A window is a contiguous region whose contents change at both ends. Fixed-width problems make removal predictable; variable-width problems require a validity condition and a repair loop. Practice ingest, repair and commit in that order, and explain when a counting problem commits several answers rather than just one.
- Maximum Fixed-Window Sum
- Count Fixed Windows Above Threshold
- Moving Average Stream
- Longest Substring Without Repeats
- Longest Substring with At Most K Distinct
- Longest Ones After K Flips
- Permutation Inclusion
- Shortest Positive Window Reaching Target
- Minimum Covering Substring
- Count Subarrays with Exactly K Distinct
Module 06. Prefix Sums, Prefix State, and Difference Arrays
Reason with array boundaries rather than repeatedly recomputing ranges.
Some interval questions can be answered without moving a window at all. Prefix summaries turn interval work into a difference or a relationship between two boundaries. The empty prefix is an actual state that often needs to be seeded. Difference arrays reverse the idea: record changes at boundaries and reconstruct their effect later.
- Build a Prefix-Sum Array
- Answer Static Range-Sum Queries
- Pivot Index
- Count Subarrays Summing to K
- Longest Subarray Summing to K
- Equal Zeros and Ones
- Product Except Self
- Range Addition with Difference Array
- Flight Bookings
- Two-Dimensional Prefix Queries
Module 07. Stacks and Expression State
Use last-in-first-out state for nested structures, unresolved neighbours, and parsing contexts.
A stack records unfinished obligations in last-in, first-out order. Delimiters, operators, deferred strings and colliding objects all have different meanings, but each next event interacts with the most recent unresolved state. Write down what a pop completes before writing the pop itself.
- Balanced Brackets
- Evaluate Postfix Notation
- Remove Adjacent Equal Pairs
- Simplify an Absolute Unix Path
- Validate Stack Push/Pop Sequences
- Design Min Stack
- Decode Nested Repetition
- Asteroid Collision
- Basic Calculator with Parentheses
- Score of Parentheses
Module 08. Monotonic Stacks and Monotonic Deques
Invert repeated future searches: let each incoming event resolve or dominate earlier pending candidates.
Monotonic structures keep only candidates that can still matter. A new value may resolve old candidates or dominate them permanently. Those are different reasons to remove an entry. Equality policy is especially important: repeated heights or minima must have a consistent owner, and window expiry is separate from value dominance.
- Next Greater Element
- Next Smaller Element
- Days Until Warmer Temperature
- Online Stock Span
- Largest Rectangle in Histogram
- Maximal Rectangle in Binary Matrix
- Sum of Subarray Minimums
- Sliding Window Maximum
- Shortest Subarray Sum At Least K with Negatives
- Remove K Digits
Module 09. Queues, Heaps, and Streaming Frontiers
Choose FIFO for breadth/order and heaps for the next globally relevant candidate or a bounded winner pool.
Choose a frontier by the next event you need. Queues expose the oldest item, stacks the newest, and heaps the highest-priority candidate. Streaming top-k and medians retain summaries instead of the whole history. Distinguish strict per-operation cost from amortized cost across a sequence.
- Queue Using Two Stacks
- Stack Using One Queue
- Recent Counter
- Largest K Values from a Stream
- Smallest K Values from a Stream
- Kth Largest Stream Class
- Top K Frequent Values
- Merge K Sorted Arrays
- K Closest Points to Origin
- Running Median
Module 10. Intervals and Sweep-Line Events
Represent durations through ordered boundaries and maintain only currently active state.
Translate intervals into ordered events. Endpoint conventions decide whether a departure and arrival at the same time overlap. Sweep-line state describes what is active between events, while interval merging summarizes completed coverage. Dynamic calendars expose an additional issue: sorted lookup may be fast even when insertion still shifts a list.
- Maximum Concurrent Intervals
- Minimum Meeting Rooms
- Car Pooling Capacity
- Total Covered Length
- Employee Free Time
- Calendar Booking I
- Calendar Maximum Overlap
- Minimum Points to Cover Intervals
- Skyline Key Points
- Active Interval Count Queries
Module 11. Linked Lists and Pointer Mutation
Treat links as the structure; preserve unread nodes before changing pointers.
Linked structures make reference ownership visible. Before replacing a next pointer, preserve the node you still need to reach. Dummy nodes remove special cases at the head; fast/slow pointers compare traversal progress. Diagrams should name objects and arrows, because equal values do not imply equal node identity.
- Build and Serialize a Singly Linked List
- Reverse a Linked List
- Merge Two Sorted Linked Lists
- Find the Middle Node
- Detect a Cycle
- Find Cycle Entry
- Remove Nth Node from End
- Reverse a Sublist
- Reorder List
- Copy List with Random Pointer
Module 12. Binary Search and Monotone Answer Spaces
Maintain a candidate interval and use one comparison or feasibility test to discard half safely.
Binary search is controlled elimination. Start from a candidate interval and a statement explaining what remains possible inside it. Exact lookup, lower bound, rotated lookup and answer-space search use related boundary mechanics but different predicates. The rotated-array lesson expands both successful branches in detail so the familiar updates retain a precise meaning.
- Exact Binary Search
- Lower Bound
- Upper Bound
- First and Last Target Position
- Integer Square Root
- Search Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
- Search a Row-Major Sorted Matrix
- Minimum Eating Speed
- Minimum Shipping Capacity
Module 13. Matrix Traversal and Simulation
Coordinate row/column indices, shrinking boundaries, and old-versus-new state in two dimensions.
A matrix adds a coordinate system, not an excuse to abandon state definitions. Name row and column meanings, traversal direction, and whether an update reads original or already-modified cells. In-place transformations depend on preserving enough old information before it is overwritten.
- Row and Column Totals
- Transpose a Matrix
- Rotate a Square Matrix Clockwise
- Spiral Traversal
- Set Matrix Zeroes
- Diagonal Zigzag Traversal
- Game of Life Step
- Matrix Reshape
- Sparse Matrix Multiplication
- Validate Sudoku Board
Module 14. Grid DFS, BFS, and Multi-Source Search
Treat cells as graph nodes, directions as edges, and marking time as part of correctness.
Grid traversal is graph traversal with implicit neighbors. Model allowed directions explicitly, then choose DFS for region consumption or BFS for shortest unit-cost distance. Multi-source BFS begins with an entire initial frontier. Mark at discovery to prevent duplicate work; reserve path-local visitation for later backtracking problems.
- Flood Fill with DFS
- Flood Fill with BFS
- Count Islands
- Maximum Island Area
- Surrounded Regions
- Rotting Oranges
- Shortest Binary-Matrix Path
- Nearest-Zero Distances
- Walls and Gates
- Pacific Atlantic Water Flow
Module 15. Recursion and Divide-and-Conquer
Define what one call returns, identify the base case, and combine smaller solved instances.
Recursion replaces a loop driver with a call contract. A child call should return a complete, named result; the parent combines it once. Practice descent and unwinding before branching into many choices. Divide-and-conquer adds a proof that smaller solved pieces can be combined without losing order or duplicating work.
- Factorial with Call Trace
- Sum a Nested List
- Flatten a Nested List
- Reverse a String Recursively
- Fast Exponentiation
- Merge Sort
- Quicksort Partition
- Quickselect Kth Statistic
- Tower of Hanoi
- Merge K Sorted Arrays by Divide-and-Conquer
Module 16. Backtracking and Combinatorial Search
Represent a partial candidate, enumerate legal choices, restore shared state, and prune impossible branches.
Backtracking explores alternative histories. Unlike permanent graph visitation, a chosen value or reserved cell belongs to one path and must be restored before its sibling starts. Use choose, explore, undo as an ownership protocol. Pruning is justified only when the rejected prefix cannot lead to a valid completed answer.
- Generate Binary Strings
- Generate All Subsets
- Choose K Combinations
- Generate Permutations
- Generate Unique Permutations
- Combination Sum
- Generate Balanced Parentheses
- Word Search in Grid
- Palindrome Partitioning
- N-Queens
Module 17. Binary Trees: Recursive DFS and Structural Contracts
Make each recursive call promise one precise fact about its subtree and combine answers bottom-up.
A tree makes recursive subproblems structural: the left and right child subtrees are already disjoint. Traversal order depends on when the parent acts. Summary problems require a stronger call contract. Height is an upward contribution; diameter is a completed path, so a single variable cannot serve both meanings.
- Build and Serialize a Binary Tree
- Maximum Depth
- Recursive Preorder Traversal
- Recursive Inorder Traversal
- Recursive Postorder Traversal
- Same Tree
- Invert Binary Tree
- Diameter of Binary Tree
- Balanced Binary Tree
- Root-to-Leaf Target Sum
Module 18. Tree BFS, Binary Search Trees, and Tries
Use level frontiers, ordering invariants, and prefix trees for hierarchical search.
Different tree tasks exploit different structure. BFS groups by depth, BST search carries value-order constraints, and a trie consumes a character prefix along edges. Do not assume a generic binary tree is sorted. Wildcard trie search reconnects hierarchical lookup with the branching discipline from backtracking.
- Binary Tree Level Order
- Minimum Tree Depth with BFS
- Right Side View
- Zigzag Level Order
- Validate a BST
- Kth Smallest in BST
- Lowest Common Ancestor in BST
- Sorted Array to Balanced BST
- Implement Trie
- Wildcard Word Dictionary
Module 19. Graph Traversal and Connected Components
Identify nodes/edges explicitly, select DFS or BFS, and mark discovery at the correct time.
Make vertices, edges, direction and identity explicit before traversing a graph. Discovery must happen when work is scheduled. Reachability uses permanent visitation; path enumeration may revisit a shared descendant through another route. BFS shortest-hop reasoning depends on every edge having the same cost.
- Build an Adjacency List
- DFS Reachability
- BFS Shortest Hops
- Count Graph Components
- Clone a Graph
- Validate an Undirected Tree
- Bipartite Graph Check
- All Paths from Source to Target in DAG
- Number of Provinces
- Word Ladder Length
Module 20. Directed Graphs, Cycles, and Topological Order
Model prerequisite relationships and distinguish nodes currently on the DFS path from fully finished nodes.
Directed dependencies require a distinction between active recursion and completed work. Topological order turns a DAG into a valid computation schedule. Once that schedule is known, ancestor sets, path values and downstream effects become dynamic programs over vertices. Shared dependencies require set union rather than blindly adding counts.
- Detect a Directed Cycle with Three States
- Course Schedule Feasibility
- Return One Course Order
- Minimum Semesters
- Eventual Safe Nodes
- Longest Path in a DAG
- Prerequisite Reachability Queries
- Alien Dictionary Order
- Reconstruct Itinerary
- Dependency Impact Counts
Module 21. Union-Find, Weighted Graphs, and Minimum Spanning Trees
Maintain dynamic components and use priority frontiers for weighted shortest paths or minimum connection cost.
Connectivity, minimum connection cost and shortest travel cost are different questions. DSU summarizes which components are joined. Kruskal and Prim choose safe connection edges; Dijkstra prioritizes accumulated path length. Edge-budgeted flights need another state axis, while zero/one weights permit a cheaper deque frontier.
- Implement Disjoint-Set Union
- Count Components with Union-Find
- Redundant Connection
- Accounts Merge
- Kruskal Minimum Spanning Tree
- Prim Minimum Spanning Tree
- Dijkstra Shortest Paths
- Network Delay Time
- Cheapest Flight Within K Stops
- Zero-One BFS
Module 22. Greedy Algorithms and Kadane-Style State
Recognize when one compact frontier or a locally safe choice summarizes all useful history.
A greedy rule needs an exchange or dominance argument, not just a plausible choice. Earliest finishing intervals leave room for later choices; a failed gas-station prefix rules out several starts at once. Some one-pass recurrences also prepare the next chapter: distinguish the best answer ending here from the best answer anywhere.
- Best Single Stock Transaction
- Maximum Subarray Sum
- Maximum Product Subarray
- Maximum Circular Subarray
- Jump Game Reachability
- Minimum Jumps to End
- Gas Station Circuit
- Maximum Number of Non-overlapping Intervals
- Partition Labels
- Task Scheduler with Cooldown
Module 23. Dynamic Programming I: One-Dimensional State
Define one subproblem precisely, derive its recurrence, set base cases, and choose a valid computation order.
Define one subproblem before optimizing its storage. Prefix length, exact amount and endpoint index describe different states and lead to different recurrences. Base cases are part of the model, especially the empty prefix. Only compress a table after you can identify which previous answers every update must still read.
- Fibonacci with Rolling State
- Climbing Stairs
- Minimum Cost Climbing Stairs
- House Robber
- House Robber II
- Decode Ways
- Word Break
- Minimum Coin Change
- Coin-Change Combination Count
- Longest Increasing Subsequence
Module 24. Dynamic Programming II: Grids, Knapsack, and Strings
Give every DP axis a precise meaning and derive transitions from neighbouring or smaller states.
Every DP axis needs a sentence. Grid coordinates, item/capacity pairs, two prefix lengths and interval endpoints encode different dependency graphs. Loop order is a topological order of those states. In one-dimensional knapsack compression, reversing capacity order is what preserves the previous item layer.
- Unique Grid Paths
- Minimum Path Sum
- Unique Paths with Obstacles
- Zero-One Knapsack
- Partition Equal Subset Sum
- Target Sum Ways
- Longest Common Subsequence
- Edit Distance
- Interleaving String
- Longest Palindromic Subsequence
Module 25. Bit Manipulation, Mathematics, and Designed Data Structures
Use algebraic identities and maintain multi-operation invariants in stateful classes.
Finish with algebraic summaries and persistent multi-operation state. XOR cancels paired information; Euclid preserves a mathematical identity. RandomizedSet, LRU and TimeMap combine structures whose invariants must agree after every operation. The final timestamp search returns to the half-open boundary discipline developed earlier.