Common Problem-Solving Patterns
This guide covers the 16 essential algorithmic patterns found across the top 100 interview problems. Understanding these patterns helps you recognize problem types instantly and apply the right approach.Pattern Overview
The 16 core patterns are:- Array & Hashing - Fast lookups and aggregations
- Two Pointers - Linear traversal optimization
- Sliding Window - Subarray/substring optimization
- Stack - LIFO operations and parsing
- Binary Search - Logarithmic search in sorted spaces
- Linked List - Sequential pointer manipulation
- Trees - Hierarchical data traversal
- BST - Binary search tree properties
- Heap/Priority Queue - Dynamic min/max tracking
- Graph DFS - Deep exploration and cycles
- Graph BFS - Shortest paths and levels
- Dynamic Programming - Optimal substructure
- Backtracking - Exhaustive search with pruning
- Greedy - Local optimal choices
- Bit Manipulation - Efficient bitwise operations
- Math & Geometry - Mathematical insights
1. Array & Hashing
When to Use
- Need O(1) lookups or counting
- Finding pairs, duplicates, or frequencies
- Prefix sums for range queries
- Grouping or aggregating data
Key Techniques
- Hash Map: O(1) lookups for complements
- Prefix Sum: Cumulative sums for range queries
- Sorting: Enable two-pointer or binary search
- Counting: Frequency maps for analysis
Code Template
Problems Using This Pattern
2. Two Pointers
When to Use
- Array is sorted or can be sorted
- Finding pairs with a condition
- In-place array manipulation
- Palindrome checking
- Merging sorted sequences
Key Variations
- Opposite Direction: Start from both ends (palindrome, container)
- Same Direction: Fast/slow pointers (remove duplicates)
- Fixed Gap: Maintain distance between pointers
Code Template
Problems Using This Pattern
3. Sliding Window
When to Use
- Contiguous subarray/substring problems
- Finding minimum/maximum with constraints
- “At most K” or “exactly K” conditions
- Optimizing brute force O(n²) to O(n)
Key Variations
- Fixed Size: Window size is constant
- Variable Size: Expand/contract based on condition
- Hash Map: Track character frequencies
Code Template
Problems Using This Pattern
- #037 - Minimum Window Substring
- #040 - Max Consecutive Ones III
- #080 - Longest Substring Without Repeating Characters
- #068 - Contains Duplicate II
4. Stack
When to Use
- Parsing expressions or parentheses
- Matching pairs (brackets, tags)
- Monotonic sequences (next greater/smaller)
- Undo/redo operations
- Function call tracking
Key Variations
- Matching Stack: Store opening brackets
- Monotonic Stack: Maintain increasing/decreasing order
- Index Stack: Store indices instead of values
- State Stack: Track complex states
Code Template
Problems Using This Pattern
- #020 - Valid Parentheses
- #001 - Minimum Remove to Make Valid Parentheses
- #008 - Basic Calculator II
- #093 - Decode String
5. Binary Search
When to Use
- Search in sorted array
- Find first/last occurrence
- Search in rotated sorted array
- Minimize/maximize with validation function
- Answer is in a bounded range
Key Variations
- Search Target: Find exact value in sorted array
- Search Answer Space: Binary search on answer range
- Search Condition: Find boundary meeting condition
Code Template
Problems Using This Pattern
- #010 - Find Peak Element
- #042 - Find First and Last Position
- #079 - Capacity To Ship Packages
- #094 - Koko Eating Bananas
6. Linked List
When to Use
- Sequential data with insertions/deletions
- Detecting cycles
- Finding middle element
- Reversing sequences
- Merging sorted lists
Key Techniques
- Dummy Node: Simplify edge cases
- Fast/Slow Pointers: Find middle or detect cycle
- Two Pointer Gap: Remove nth from end
- In-place Reversal: Reverse without extra space
Code Template
Problems Using This Pattern
- #019 - Merge k Sorted Lists
- #032 - Copy List with Random Pointer
- #045 - Remove Nth Node From End
- #054 - Add Two Numbers
7. Binary Tree Traversal
When to Use
- Tree structure problems
- Finding paths or levels
- Computing tree properties
- Serialization/deserialization
Key Techniques
- DFS (Pre/In/Post-order): Recursive or stack-based
- BFS (Level-order): Queue-based traversal
- Bottom-up: Return values from children
- Top-down: Pass values to children
Code Template
Problems Using This Pattern
- #007 - Binary Tree Right Side View
- #014 - Diameter of Binary Tree
- #003 - Binary Tree Vertical Order Traversal
- #076 - Binary Tree Maximum Path Sum
8. Binary Search Tree
When to Use
- BST property: left < root < right
- Finding kth smallest/largest
- Validating BST
- Range queries
- Closest value searches
Key Techniques
- Inorder Traversal: Gives sorted order
- BST Property Pruning: Skip subtrees
- Iterative Navigation: Use BST property for O(h) search
Code Template
Problems Using This Pattern
- #027 - Range Sum of BST
- #060 - Closest Binary Search Tree Value
- #092 - Kth Smallest Element in BST
- #051 - Binary Search Tree Iterator
9. Heap / Priority Queue
When to Use
- Find kth largest/smallest dynamically
- Merge k sorted sequences
- Top k frequent elements
- Median tracking
- Scheduling problems
Key Variations
- Min Heap: Track k largest (size k min heap)
- Max Heap: Track k smallest (negate values)
- Dual Heap: Median maintenance (max + min heap)
Code Template
Problems Using This Pattern
- #006 - Kth Largest Element in an Array
- #019 - Merge k Sorted Lists
- #015 - Top K Frequent Elements
- #082 - Find Median from Data Stream
10. Graph DFS
When to Use
- Explore all paths or components
- Detect cycles
- Topological sorting
- Connected components
- Backtracking on graphs
Key Techniques
- Visited Set: Track explored nodes
- Recursion Stack: Detect back edges (cycles)
- Backtracking: Undo state changes
- Component Labeling: Mark connected groups
Code Template
Problems Using This Pattern
11. Graph BFS
When to Use
- Shortest path (unweighted)
- Level-by-level exploration
- Minimum steps/distance
- Multi-source BFS
Key Techniques
- Queue: FIFO for level order
- Distance Tracking: Count levels/steps
- Multi-source: Start from multiple nodes
- Visited Set: Avoid revisiting
Code Template
Problems Using This Pattern
12. Dynamic Programming
When to Use
- Optimal substructure (solution built from subsolutions)
- Overlapping subproblems
- Counting ways or optimization
- “Maximum/minimum/longest” keywords
Key Approaches
- Top-down (Memoization): Recursion + cache
- Bottom-up (Tabulation): Iterative DP table
- State Compression: Optimize space
Code Template
Problems Using This Pattern
- #018 - Best Time to Buy and Sell Stock
- #075 - Word Break
- #087 - Maximum Subarray
- #099 - Best Time to Buy and Sell Stock III
Pattern Recognition Guide
When you see a problem, ask:-
Input type?
- Array/String → Two Pointers, Sliding Window, Binary Search
- Tree/Graph → DFS/BFS, Recursion
- Stream/Dynamic → Heap, Design
-
Looking for what?
- Pair/Triplet → Two Pointers, Hash Map
- Shortest path → BFS
- All paths/combinations → DFS, Backtracking
- Kth element → Heap, Binary Search
- Optimal value → DP, Greedy
-
Constraints hint?
- O(log n) required → Binary Search
- O(n) space not allowed → Two Pointers, Sliding Window
- k is small → Heap of size k
- Value range is small → Counting, Bucket Sort
-
Keywords?
- “Substring/subarray” → Sliding Window
- “Parentheses/brackets” → Stack
- “Minimum/maximum” → DP, Greedy, Heap
- “Ways to…” → DP, Backtracking
- “Sorted” → Binary Search, Two Pointers
Next Steps
- Practice Recognition: Identify patterns before coding
- Master Templates: Memorize core template for each pattern
- Study Variations: Understand when to modify templates
- Combine Patterns: Many problems use 2-3 patterns together