DSA Pattern Cheat Sheet
All 29 patterns at a glance. Filter by category, difficulty, or search by keyword.
Two Pointers
Use two pointers that move toward each other or in the same direction to efficiently search or compare elements in a sorted array or string.
- Sorted array with a target sum or condition
- Comparing elements from both ends
Sliding Window
Maintain a window of elements that slides across the array, expanding or shrinking to find optimal subarrays or substrings.
- Find longest/shortest subarray with a property
- Find substring with specific characters
Prefix Sum
Precompute cumulative sums to answer range sum queries in O(1) time after O(n) preprocessing.
- Multiple range sum queries
- Subarray sum equals target
Kadane's Algorithm
Track the maximum subarray sum ending at each position, resetting when the running sum becomes negative.
- Maximum subarray sum
- Maximum product subarray
Hash Map Counting
Use a hash map to count frequencies or track seen elements for O(1) lookups.
- Count element frequencies
- Check if element exists
Two Sum Pattern
Use a hash map to find pairs that satisfy a target condition in a single pass.
- Find pair with target sum (unsorted)
- Find complement
Cyclic Sort
Place each number at its correct index (value i at index i) by swapping, to find missing or duplicate numbers in a range [0, n] or [1, n].
- Array contains numbers in a known range [0, n] or [1, n]
- Find missing, duplicate, or corrupt numbers
Binary Search
Repeatedly halve the search space to find a target or boundary in O(log n) time.
- Sorted array search
- Find boundary (first/last occurrence)
Merge Intervals
Sort intervals by start time, then merge overlapping ones by comparing end times.
- Overlapping intervals
- Meeting room scheduling
Bucket Sort / Top-K
Use a heap (priority queue) or bucket sort to efficiently find the K largest/smallest/most frequent elements.
- Find top K elements
- K most frequent
Two Heaps
Use a max-heap and a min-heap together to efficiently track the median or partition elements into two balanced groups.
- Find median of a data stream
- Balance elements into two halves
K-way Merge
Merge K sorted arrays or lists using a min-heap to always pick the globally smallest element across all lists.
- Merge K sorted arrays or linked lists
- Find the smallest range covering K lists
Fast & Slow Pointers
Use two pointers moving at different speeds to detect cycles, find midpoints, or determine list properties.
- Cycle detection in linked list
- Find middle of linked list
Linked List Reversal
Reverse a linked list (or sublist) by reassigning next pointers while traversing.
- Reverse entire linked list
- Reverse k-group or sublist
BFS (Level-Order)
Explore all nodes at the current depth before moving to the next level, using a queue.
- Level-order traversal
- Shortest path in unweighted graph
DFS (Pre/In/Post-Order)
Explore as deep as possible along each branch before backtracking. Use pre-order, in-order, or post-order depending on when you process the node.
- Tree traversal (any order)
- Path-related problems
Backtracking
Build solutions incrementally, abandoning a path as soon as it cannot lead to a valid solution.
- Generate all permutations/combinations
- Constraint satisfaction (Sudoku, N-Queens)
Topological Sort
Order vertices of a directed acyclic graph (DAG) so every edge goes from earlier to later in the ordering.
- Task scheduling with dependencies
- Course prerequisites
Union-Find
Track disjoint sets using parent pointers with path compression and union by rank for near O(1) operations.
- Connected components
- Detect cycle in undirected graph
0/1 Knapsack
Choose items (take or skip each) to maximize value within a capacity constraint.
- Select subset with weight/capacity constraint
- Maximize/minimize value with constraints
Unbounded Knapsack
Like 0/1 Knapsack, but each item can be used unlimited times.
- Unlimited supply of items
- Coin change problem
Fibonacci Pattern
Each state depends on a fixed number of previous states, like Fibonacci numbers.
- Climbing stairs
- House robber
Longest Common Subsequence
Compare two sequences and build a 2D DP table where each cell represents the optimal answer for prefixes of both sequences.
- Compare two strings/sequences
- Edit distance
DP on Trees
Apply dynamic programming on tree structures using post-order DFS, where each node's answer depends on its children's answers.
- Optimal value on tree paths
- Tree diameter
Monotonic Stack/Queue
Maintain a stack or deque where elements are always in sorted order, enabling efficient next-greater/smaller element queries.
- Next greater/smaller element
- Largest rectangle in histogram
Trie
A tree-like data structure where each node represents a character and paths from root to nodes form prefixes. Tries enable O(m) insert, search, and prefix queries (m = word length), making them ideal for dictionaries, autocomplete, spell checking, and word search problems where multiple strings share common prefixes.
- Prefix-based search
- Autocomplete / word suggestions
Greedy
Make the locally optimal choice at each step, trusting that it leads to a globally optimal solution. Greedy works when two properties hold: (1) greedy choice property — a local optimum is part of a global optimum, and (2) optimal substructure — an optimal solution contains optimal solutions to subproblems. Common in scheduling, interval selection, and jump/reachability problems.
- Activity selection / scheduling
- Jump games / reachability
Bit Manipulation
Use bitwise operations (AND, OR, XOR, shift) for efficient computation on integers.
- Find single/unique number
- Power of two checks
Matrix / Grid DP
Fill a 2D DP table where each cell represents the optimal answer for reaching that position in a grid, using values from adjacent cells.
- Find min/max cost path in a grid
- Count unique paths with obstacles