Pattern-Based Problem Solving

DSA Pattern Guide

Patterns are the skeleton of every algorithm. Learn the skeleton once, and you can apply it to hundreds of problems. This guide maps every pattern to the problems in this repository - 38,000+ problems, organized by the shape of their solution.

What Are DSA Patterns?

Why Patterns Matter

Most DSA problems are not truly unique. They are variations of a smaller set of structural patterns. When you recognise the pattern behind a problem, you already know 80% of the solution. The remaining 20% is adapting the template to the specific twist.

Patterns > Memorisation

Nobody remembers 38,000 solutions. But you can remember 40 patterns and derive the rest. This is how strong engineers think: they don't brute-force recall solutions, they identify the structure of the problem and pick the matching template.

One Problem, Multiple Patterns

Many problems sit at the intersection of multiple patterns. A problem might use sliding window for the outer loop and a hash map for the inner state. This guide marks primary and secondary pattern assignments, so you see how patterns compose.

Built from real data. Every pattern in this guide is mapped against the repository's actual problem list - 38,000+ problems across 50+ platforms. This is not a generic internet list. If a problem doesn't fit a pattern, the guide says so.
What This Page Is Not
  • This is not the /learn section. /learn is a separate learning path. /pattern is a structural reference map.
  • This is not a generic copy-pasted list of 14 or 16 patterns from a blog post. The taxonomy comes from this repository's 38,000+ problems.
  • This is not forcing every problem into exactly one category. Many problems belong to multiple patterns and are tagged accordingly.
  • This is not a one-page theory dump. Each pattern has its own page with templates, variants, problem mappings, and practice order.
  • This is not a solved puzzle guide that gives away answers. It teaches you how to think so you can solve unseen problems.
Pattern Taxonomy

The patterns below are grouped by experience level - not by data structure or topic. This is intentional: you should learn patterns in an order that builds on itself. Each level assumes comfort with the patterns before it.

Beginner Foundation8 patterns
BeginnerNeeds Mapping

Hash Map / Frequency Counting

Use a hash map to count occurrences, track pair sums, or detect duplicates in O(1) average lookup time. The bread and butter of O(n) solutions.

HashMapHashSetArray
3,200problems
O(n) time, O(k) space
BeginnerReady

Two Pointers

Two indices moving through a sequence - opposite direction or same direction. Turns O(n²) comparisons into O(n) by maintaining an invariant about pointer positions.

ArrayString
2,500problems
O(n) time, O(1) space
BeginnerReady

Sliding Window

Maintain a window over a contiguous segment of an array/string. Expand the right edge, shrink the left edge when the window becomes invalid. Turns O(n²) subarray enumeration into O(n).

ArrayStringDeque
610problems
O(n) time, O(1) or O(k) space
BeginnerNeeds Mapping

Prefix Sum

Precompute running sums so that sum(l..r) = prefix[r] - prefix[l-1] in O(1). Works with hash maps to count subarrays matching a target.

ArrayHashMap
1,800problems
O(n) precompute, O(1) query
BeginnerNeeds Mapping

Sorting-Based Patterns

Sorting is not a pattern itself, but many problems become trivial once the input is sorted. Sort + two pointers, sort + greedy, sort + binary search - the prep step that unlocks linear passes.

Array
4,000problems
O(n log n) sort + O(n) pass
BeginnerNeeds Mapping

Stack

Last-in-first-out structure. Used for matching problems (parentheses), undo operations, expression evaluation, and maintaining a history of elements to compare against later elements.

StackArray
1,500problems
O(n) time, O(n) space
BeginnerNeeds Mapping

Queue

First-in-first-out structure. Used for level-order traversal, BFS, streaming data, and maintaining elements in arrival order.

QueueDequeLinkedList
800problems
O(n) time, O(n) space
BeginnerReady

Binary Search

Repeatedly divide the search space in half. Works when the search space is monotonic - sorted arrays, or any predicate that transitions from false to true.

Array
3,709problems
O(log n) time, O(1) space
Core Intermediate11 patterns
IntermediateReady

Linked List Patterns

Dummy nodes, reversal, slow/fast pointers, merging, partitioning. Linked lists enforce sequential access, so the patterns focus on pointer manipulation and two-pass techniques.

SinglyLinkedListDoublyLinkedListDummyNode
1,135problems
O(n) time, O(1) space
IntermediateNeeds Mapping

Recursion

Solve a problem by solving smaller instances of the same problem. Every recursive solution needs a base case and a recurrence that moves toward the base. The foundation for trees, DP, backtracking.

CallStack
3,000problems
Varies - O(n) to O(2ⁿ)
IntermediateReady

Backtracking

Explore all candidate solutions by building incrementally and abandoning (pruning) paths that cannot lead to a valid solution. State space search with undo.

ArraySetStack
325problems
O(n!) or O(2ⁿ) worst case with pruning
IntermediateNeeds Mapping

Tree DFS

Recursive depth-first traversal of a tree. Pre-order (process before children), in-order (process between children - gives sorted order in BST), post-order (process after children - need child results first).

BinaryTreeStackRecursion
2,000problems
O(n) time, O(h) space
IntermediateNeeds Mapping

Tree BFS / Level Order

Queue-based level-by-level traversal of a tree. Process all nodes at depth d before depth d+1. Level averages, right side view, zigzag, connect siblings.

QueueBinaryTreeArray
800problems
O(n) time, O(w) width
IntermediateReady

Matrix Traversal

Iterating a 2D grid systematically - row-major, spiral order, diagonal traversal, neighbor iteration with delta arrays (dr/dc). Often combined with BFS/DFS.

MatrixQueueSet
331problems
O(m×n) time, O(1) or O(m×n) space
IntermediateNeeds Mapping

Graph DFS

Recursive or stack-based depth-first graph traversal. Mark visited on entry. Count connected components, detect cycles (track parent undirected, path[] for directed), topological sort via post-order.

AdjacencyListStackVisitedArray
1,200problems
O(V + E) time, O(V) space
IntermediateNeeds Mapping

Graph BFS

Queue-based breadth-first graph traversal. Guarantees shortest path in unweighted graphs. Level-by-level expansion. Multi-source variant: enqueue all sources at level 0.

AdjacencyListQueueDistanceArray
1,000problems
O(V + E) time, O(V) space
IntermediateReady

Heap / Priority Queue

Always extract the min/max element in O(log n). Used for top-K, median finding, Dijkstra, merge K sorted lists, scheduling, and anytime you need repeated extreme-value queries.

MinHeapMaxHeapPriorityQueue
496problems
O(n log k) or O((V+E) log V)
IntermediateNeeds Mapping

Intervals

Sort by start time, then merge, intersect, or compare adjacent intervals. Overlap check: max(start1, start2) < min(end1, end2). Sweep-line for complex coverage.

ArraySortedList
600problems
O(n log n) sort, O(n) pass
IntermediateReady

Greedy

Make the locally optimal choice at each step, trusting it leads to the global optimum. Works when the problem has optimal substructure and a greedy choice property. Classic: interval scheduling, coin change (canonical).

ArraySorting
2,000problems
O(n log n) typically
Pattern Decision Tree
Start with a problem...

├── Is it about counting or looking up something fast?
│   └── ✓ Hash Map / Frequency Counting
│
├── Is the input a sorted array or string?
│   ├── Looking for a pair with a target?           → Two Pointers
│   ├── Looking for a contiguous subarray/substring? → Sliding Window
│   └── Looking for a specific value?                → Binary Search
│
├── Can you precompute something to answer queries fast?
│   └── ✓ Prefix Sum, Difference Array, Rolling Hash
│
├── Does the problem ask for all permutations/combinations/subsets?
│   └── ✓ Backtracking
│
├── Is it a tree?
│   ├── Need to process level-by-level?              → Tree BFS
│   ├── Need child results before parent decision?   → Tree DFS (post-order)
│   ├── Need sorted order from BST?                  → Tree DFS (in-order)
│   └── Path query between two nodes?                → LCA / Binary Lifting
│
├── Is it a graph?
│   ├── Shortest path in unweighted graph?           → Graph BFS
│   ├── Shortest path in weighted graph?             → Dijkstra
│   ├── Connected components?                        → Graph DFS or DSU
│   ├── Cycle detection?                             → DFS + vis/path or DSU
│   ├── Topological order?                           → Kahn's / DFS post-order
│   ├── All-pairs shortest?                          → Floyd-Warshall
│   └── Minimum cost to connect all?                 → MST (Kruskal/Prim)
│
├── Is it a linked list?
│   ├── Detect cycle / find middle?                  → Fast & Slow Pointers
│   ├── Reverse / merge / remove?                    → Dummy Node + Iteration
│   └── Palindrome / reorder?                        → Slow/Fast + Reverse
│
├── Does it ask for max/min under a constraint?
│   ├── Choose or skip items?                        → DP or Greedy
│   ├── Can you check feasibility of a candidate?    → Binary Search on Answer
│   └── Locally optimal choice works?                → Greedy
│
├── Is there optimal substructure with overlapping subproblems?
│   └── ✓ Dynamic Programming (1D → 2D → Tree → etc.)
│
├── Does it involve next/previous greater/smaller?
│   └── ✓ Monotonic Stack
│
├── Sliding window with min/max tracking?
│   └── ✓ Monotonic Queue / Deque
│
├── Top K, median, or merge K sorted?
│   └── ✓ Heap / Priority Queue
│
├── String matching / prefix search?
│   └── ✓ Trie, KMP, Z-Algorithm, Rolling Hash
│
├── Range queries with updates?
│   └── ✓ Segment Tree or Fenwick Tree
│
├── Range queries without updates?
│   └── ✓ Prefix Sum, Difference Array, Sparse Table
│
├── Bit-level operations / subset enumeration?
│   └── ✓ Bit Manipulation, Bitmask DP
│
├── Game with two optimal players?
│   └── ✓ Game Theory / Minimax / Grundy
│
└── None of the above?
    └── Could be Simulation, Ad-hoc, Math, or a combination of patterns
Visualisation todo: Each pattern page should eventually have an animated diagram showing how the algorithm moves through data - sliding window movement, pointer traversal, recursion tree, graph BFS expansion, DP state transitions, etc. These will be added as the site grows.
How to Use This Guide
01

Pick a Pattern

Start with a Beginner pattern (hash map, two pointers, sliding window). Read the pattern page - understand the mental model, not just the code.

02

Learn the Template

Each pattern has a core template. This is the skeleton. Understand why each line exists, what invariant it maintains, and when the template breaks.

03

Study the Variants

Templates have variants. The core idea stays the same but the details shift - fixed vs dynamic window, opposite vs same-direction pointers. Each variant opens a new class of problems.

04

Solve the Mapped Problems

Each pattern page lists problems from this repository that fit the template and each variant. Solve them in the recommended order: beginner → intermediate → advanced.

05

Track Your Coverage

Mark which problems you have solved. The goal is not to solve every problem - it is to internalise the pattern so thoroughly that new problems feel familiar within seconds.

06

Repeat

When you get stuck on a new problem, come back to this guide. Find the pattern that matches the shape of your problem. Read the page again. It will make more sense each time.

Recommended Learning Roadmap
Beginner Foundation8 patterns
Hash Map / Frequency CountingTwo PointersSliding WindowPrefix SumSorting-Based PatternsStackQueueBinary Search

Build the reflexes. These patterns alone can solve ~40% of interview problems. Focus on recognising the signal phrases for each one.

Core Intermediate11 patterns
Linked List PatternsRecursionBacktrackingTree DFSTree BFSMatrix TraversalGraph DFSGraph BFSHeap / Priority QueueIntervalsGreedy

These are the patterns that separate scripted solutions from genuine problem-solving ability. Trees and graphs appear in ~30% of interviews.

Advanced Intermediate8 patterns
Monotonic StackMonotonic Queue / DequeBinary Search on AnswerTopological SortUnion-Find / DSUTrieDynamic ProgrammingBit Manipulation

These patterns add the sharpest tools to your belt. DP and Union-Find are common at top-tier companies. Monotonic stacks turn intimidating O(n²) problems into clean O(n) walks.

Advanced16 patterns
Knapsack DPInterval DPTree DPBitmask DPDigit DPShortest Path (Dijkstra, Bellman-Ford, Floyd-Warshall)Minimum Spanning TreeSegment TreeFenwick TreeString Matching (KMP, Z, Rabin-Karp)Rolling HashMath / Number TheoryGeometryGame TheoryDesign ProblemsSimulation

These are specialist patterns. Not every interview will need them, but when they do, they separate senior engineers. Learn them if you target top companies or competitive programming.

Coverage Tracker Plan

Every pattern page in this guide maps problems from the repository's 38,000+ problem list. The mapping is done incrementally - each pattern article adds its own mappings. The tracking table below shows the current state for every pattern.

PatternProblemsLevelStatusComplexity
Sorting-Based Patterns4,000BeginnerNeeds MappingO(n log n) sort + O(n) pass
Binary Search3,709BeginnerReadyO(log n) time, O(1) space
Hash Map / Frequency Counting3,200BeginnerNeeds MappingO(n) time, O(k) space
Two Pointers2,500BeginnerReadyO(n) time, O(1) space
Prefix Sum1,800BeginnerNeeds MappingO(n) precompute, O(1) query
Stack1,500BeginnerNeeds MappingO(n) time, O(n) space
Queue800BeginnerNeeds MappingO(n) time, O(n) space
Sliding Window610BeginnerReadyO(n) time, O(1) or O(k) space
Recursion3,000IntermediateNeeds MappingVaries - O(n) to O(2ⁿ)
Tree DFS2,000IntermediateNeeds MappingO(n) time, O(h) space
Greedy2,000IntermediateReadyO(n log n) typically
Graph DFS1,200IntermediateNeeds MappingO(V + E) time, O(V) space
Linked List Patterns1,135IntermediateReadyO(n) time, O(1) space
Graph BFS1,000IntermediateNeeds MappingO(V + E) time, O(V) space
Tree BFS / Level Order800IntermediateNeeds MappingO(n) time, O(w) width
Intervals600IntermediateNeeds MappingO(n log n) sort, O(n) pass
Heap / Priority Queue496IntermediateReadyO(n log k) or O((V+E) log V)
Matrix Traversal331IntermediateReadyO(m×n) time, O(1) or O(m×n) space
Backtracking325IntermediateReadyO(n!) or O(2ⁿ) worst case with pruning
Math / Number Theory9,632AdvancedNeeds MappingVaries - O(√n) to O(log n)
Dynamic Programming4,313AdvancedReadyVaries - O(n), O(n²), O(n × W), etc.
Bit Manipulation2,868AdvancedReadyO(1) or O(number of bits)
Simulation2,000AdvancedNeeds MappingO(n) or O(m×n) as specified
Binary Search on Answer800AdvancedReadyO(n log M) or O(n log n log M)
Knapsack DP600AdvancedReadyO(n × W) time
Shortest Path600AdvancedNeeds MappingO((V+E) log V) Dijkstra, O(VE) Bellman-Ford, O(V³) Floyd
Union-Find / DSU500AdvancedReadyO(α(n)) amortized per operation
Design Problems500AdvancedNeeds MappingO(1) or O(log n) per operation
Monotonic Stack400AdvancedReadyO(n) time, O(n) space
Tree DP400AdvancedNeeds MappingO(n) with DFS, O(n²) with knapsack
Segment Tree400AdvancedNeeds MappingO(log n) per query/update, O(n) build
String Matching400AdvancedNeeds MappingO(n + m) KMP/Z, O(n) average Rabin-Karp
Game Theory400AdvancedNeeds MappingO(states × moves) typically
Topological Sort300AdvancedReadyO(V + E) time, O(V) space
Interval DP300AdvancedReadyO(n²) or O(n³) time
Digit DP300AdvancedReadyO(digits × states × transition)
Fenwick Tree / BIT300AdvancedNeeds MappingO(log n) per query/update
Geometry300AdvancedNeeds MappingO(n log n) for hull, O(n) for area
Rolling Hash250AdvancedNeeds MappingO(n) precompute, O(1) hash, O(log n) with binary search
Monotonic Queue / Deque200AdvancedReadyO(n) time, O(k) space
Bitmask DP200AdvancedReadyO(2ⁿ × n) or O(2ⁿ × n²)
Minimum Spanning Tree200AdvancedNeeds MappingO(E log E) Kruskal, O(E log V) Prim
Trie158AdvancedReadyO(L) per operation where L = word length
How tracking works: Each pattern article maps problems incrementally. A problem is tracked by its URL, primary pattern, secondary patterns, template variant, and last-reviewed date. The goal is not to map all 38,000+ problems instantly - it is to build reliable coverage gradually while writing each pattern article. Patterns marked "needs mapping" have not yet had their problem mapping written. Patterns marked "ready" have their mapping started or completed.
Pattern Status Guide
Ready

Pattern article is written with templates, variants, and problem mappings. Ready to study.

Needs Mapping

Pattern article structure exists but problem-to-pattern mapping from the repository is not yet done.

Needs Review

Pattern has initial mapping but needs verification. Some problems may be incorrectly assigned.

Advanced / Later

Pattern is advanced and planned for a later pass. Not a priority for the current phase.

Ready to Start?

The best place to start is Two Pointers. It is beginner-friendly, builds foundational thinking about indices and invariants, and directly leads into Sliding Window and Fast-Slow Pointer patterns. Every pattern page follows the same structure: mental model → template → variants → problem mappings.

The next pattern article will be written under /pattern/<slug>. Each article one at a time, starting with the pattern you choose above.