Hey everyone! Many of us struggle with DSA and feel overwhelmed during interview preparation. This might be because we try to solve every problem differently instead of recognizing patterns. However, if you break down DSA into clear patterns and master each one, interviews become much more manageable. So I've compiled the complete list of patterns you absolutely need to know!
Pattern 1: Sliding Window
Why This Pattern Matters:
Sliding window is one of the most frequently tested patterns in interviews. It optimizes brute force O(n²) solutions to O(n) by maintaining a window of elements and sliding it across the array/string. This pattern appears in substring problems, subarray problems, and anywhere you need to track a contiguous sequence.
When to Use:
- Finding longest/shortest substring with condition
- Subarray with target sum/property
- Maximum/minimum in subarrays of size K
- Problems with "contiguous" elements
Key Technique:
- Fixed window: Move right, slide left when window size exceeds K
- Variable window: Expand right, shrink left when condition violated
Practice Problems:
- Maximum Sum Subarray of Size K
- Longest Substring Without Repeating Characters
- Minimum Window Substring
- Longest Repeating Character Replacement
- Permutation in String
- Find All Anagrams in a String
- Fruit Into Baskets
- Longest Substring with At Most K Distinct Characters
Pattern 2: Prefix Sum
Why This Pattern Matters:
Prefix sum is a preprocessing technique that allows you to calculate range sums in O(1) time. It's crucial for subarray sum problems and appears in many optimization scenarios. This pattern is often combined with hash maps for powerful solutions to sum-related problems.
When to Use:
- Subarray sum equals K
- Range sum queries
- Finding subarrays with specific properties
- 2D matrix sum queries
Key Technique:
prefixSum[i] = arr[0] + arr[1] + ... + arr[i]
sum(i, j) = prefixSum[j] - prefixSum[i-1]
Practice Problems:
- Subarray Sum Equals K
- Contiguous Array
- Range Sum Query - Immutable
- Range Sum Query 2D - Immutable
- Product of Array Except Self
- Find Pivot Index
- Subarray Sums Divisible by K
Pattern 3: Two Pointers
Why This Pattern Matters:
Two pointers is your go-to technique for array/string problems that require comparing or processing elements from different positions. It reduces time complexity from O(n²) to O(n) in many cases. This is one of the most versatile patterns - works on sorted arrays, palindromes, and partitioning problems.
When to Use:
- Sorted array problems
- Palindrome checking
- Pair/triplet sum problems
- Removing duplicates
- Partitioning arrays
Key Technique:
- Opposite direction: Start from both ends, move toward center
- Same direction: Both pointers move forward at different speeds
Practice Problems:
- Two Sum II - Sorted Array
- 3Sum
- Container With Most Water
- Valid Palindrome
- Remove Duplicates from Sorted Array
- Trapping Rain Water
- Sort Colors
Pattern 4: Fast & Slow Pointers
Why This Pattern Matters:
Fast and slow pointers (tortoise and hare) is an elegant technique for detecting cycles and finding middle elements in linked lists. It uses O(1) space where naive approaches need O(n). This pattern is a favorite in interviews because it tests your understanding of pointer manipulation.
When to Use:
- Cycle detection in linked lists
- Finding middle of linked list
- Finding cycle start point
- Happy number problems
- Palindrome linked list
Key Technique:
- Slow moves 1 step, fast moves 2 steps
- If cycle exists, they'll meet
- After meeting, reset one to head to find cycle start
Practice Problems:
- Linked List Cycle
- Linked List Cycle II
- Middle of the Linked List
- Happy Number
- Palindrome Linked List
- Reorder List
Pattern 5: LinkedList In-place Reversal
Why This Pattern Matters:
Reversing linked lists in-place is a fundamental skill that appears frequently in interviews. It requires careful pointer manipulation and tests your understanding of linked list structure. Once you master the basic reversal, variations become straightforward.
When to Use:
- Reverse entire linked list
- Reverse part of linked list
- Reverse in groups of K
- Reorder linked list
Key Technique:
prev = null, curr = head
while (curr != null) {
next = curr.next
curr.next = prev
prev = curr
curr = next
}
Practice Problems:
- Reverse Linked List
- Reverse Linked List II
- Reverse Nodes in k-Group
- Swap Nodes in Pairs
- Reorder List
- Rotate List
Pattern 6: Monotonic Stack
Why This Pattern Matters:
Monotonic stack maintains elements in increasing or decreasing order, allowing you to find next/previous greater/smaller elements efficiently. This pattern transforms O(n²) brute force solutions into O(n). It's particularly elegant once you understand when to push and when to pop.
When to Use:
- Next greater/smaller element
- Previous greater/smaller element
- Histogram problems
- Temperature problems
- Stock span problems
Key Technique:
- Increasing stack: Pop when current > stack.top()
- Decreasing stack: Pop when current < stack.top()
- Store indices rather than values for more info
Practice Problems:
- Next Greater Element I
- Next Greater Element II
- Daily Temperatures
- Largest Rectangle in Histogram
- Trapping Rain Water
- Online Stock Span
- Sum of Subarray Minimums
Pattern 7: Top K Elements
Why This Pattern Matters:
Finding top K elements is extremely common in real-world applications and interviews. Using a heap of size K gives O(n log k) complexity, which is much better than sorting O(n log n) when K is small. This pattern appears in recommendation systems, analytics, and optimization problems.
When to Use:
- K largest/smallest elements
- K most frequent elements
- K closest points
- Median finding
- Merging K sorted lists
Key Technique:
- K largest → Use min heap of size K
- K smallest → Use max heap of size K
- Maintain heap size = K, replace root if better element found
Practice Problems:
- Kth Largest Element in an Array
- Top K Frequent Elements
- K Closest Points to Origin
- Find Median from Data Stream
- Merge K Sorted Lists
- Kth Smallest Element in a Sorted Matrix
Pattern 8: Overlapping Intervals (Merge Intervals)
Why This Pattern Matters:
Interval problems are ubiquitous in scheduling, calendar, and resource allocation scenarios. The key insight is to sort intervals first, then merge/process in a single pass. This pattern appears in meeting rooms, flight bookings, and timeline problems.
When to Use:
- Merging intervals
- Finding overlapping intervals
- Interval insertion
- Meeting room problems
- Scheduling conflicts
Key Technique:
- Sort intervals by start time
- Iterate and check if current overlaps with previous
- Merge or count as needed
Practice Problems:
- Merge Intervals
- Insert Interval
- Non-overlapping Intervals
- Meeting Rooms
- Meeting Rooms II
- Minimum Number of Arrows to Burst Balloons
- Car Pooling
Pattern 9: Modified Binary Search
Why This Pattern Matters:
Binary search isn't just for finding elements in sorted arrays. Modified binary search applies the same principle to rotated arrays, search space reduction, and optimization problems. Recognizing when a problem can use binary search on the "answer space" is a key skill.
When to Use:
- Rotated sorted arrays
- Peak finding
- Search in 2D matrix
- Finding square root
- Capacity optimization problems
- "Minimum/maximum value such that..."
Key Technique:
- Identify monotonic property
- Binary search on answer space
- Check feasibility in O(n) or less
Practice Problems:
- Binary Search
- Search in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
- Search a 2D Matrix
- Find Peak Element
- Capacity To Ship Packages Within D Days
- Koko Eating Bananas
Pattern 10: Binary Tree Traversal
Why This Pattern Matters:
Tree traversal is fundamental to all tree problems. Understanding the three main traversals (inorder, preorder, postorder) and level-order traversal is essential. Each traversal has specific use cases - inorder for BST, preorder for copying, postorder for deletion, level-order for shortest path.
When to Use:
- Process all nodes in specific order
- Inorder: BST sorted order, validation
- Preorder: Tree serialization, copying
- Postorder: Tree deletion, dependency resolution
- Level-order: Shortest path, level-wise processing
Key Technique:
- DFS: Recursion or stack (inorder, preorder, postorder)
- BFS: Queue (level-order)
Practice Problems:
- Binary Tree Inorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Level Order Traversal
- Binary Tree Zigzag Level Order Traversal
- Validate Binary Search Tree
Pattern 11: Depth-First Search (DFS)
Why This Pattern Matters:
DFS explores as deep as possible before backtracking. It's your go-to for tree problems, graph cycle detection, path finding, and exploring all possibilities. DFS is particularly elegant with recursion and forms the basis for backtracking problems.
When to Use:
- Tree depth/height problems
- Path sum problems
- Cycle detection
- Connected components
- Topological sort
- Graph coloring
Key Technique:
- Mark visited
- Process current node
- Recursively visit neighbors
- Unmark if backtracking needed
Practice Problems:
- Maximum Depth of Binary Tree
- Path Sum
- Number of Islands
- Clone Graph
- Course Schedule
- Pacific Atlantic Water Flow
- Longest Increasing Path in a Matrix
Pattern 12: Breadth-First Search (BFS)
Why This Pattern Matters:
BFS explores level by level, guaranteeing shortest path in unweighted graphs. It's essential for level-order problems, shortest path problems, and minimum step problems. The queue-based implementation is intuitive and appears in many real-world scenarios like social networks and maze solving.
When to Use:
- Shortest path in unweighted graph
- Level-order traversal
- Minimum steps/moves problems
- Connected components
- "Nearest" problems
Key Technique:
- Use queue
- Add start node(s)
- Process level by level
- Track visited to avoid cycles
Practice Problems:
- Binary Tree Level Order Traversal
- Rotting Oranges
- 01 Matrix
- Word Ladder
- Shortest Path in Binary Matrix
- As Far from Land as Possible
Pattern 13: Matrix Traversal
Why This Pattern Matters:
Matrix problems are just graph problems in disguise - each cell is a node, and adjacent cells are neighbors. Once you see this connection, grid problems become straightforward graph traversal. This pattern is extremely common in interviews and tests your ability to handle 2D arrays and boundary conditions.
When to Use:
- Island problems
- Flood fill
- Path finding in grid
- Region identification
- Any 2D grid problem
Key Technique:
- Treat as graph with 4 or 8 neighbors
- DFS or BFS from each unvisited cell
- Watch for boundaries
Practice Problems:
- Number of Islands
- Max Area of Island
- Surrounded Regions
- Pacific Atlantic Water Flow
- Word Search
- Shortest Path in Binary Matrix
- Number of Closed Islands
Pattern 14: Backtracking
Why This Pattern Matters:
Backtracking explores all possible solutions by making choices, exploring consequences, and undoing choices if they don't work. It's essential for permutations, combinations, subsets, and constraint satisfaction problems. While potentially exponential, it's often the only way to solve certain problems.
When to Use:
- Generate all permutations/combinations
- Subset problems
- Sudoku, N-Queens
- String partitioning
- Path finding with constraints
Key Technique:
- Make a choice
- Explore with that choice (recurse)
- Undo the choice (backtrack)
- Try next choice
Practice Problems:
- Subsets
- Permutations
- Combination Sum
- Generate Parentheses
- Letter Combinations of a Phone Number
- Palindrome Partitioning
- N-Queens
- Word Search
Pattern 15: Dynamic Programming
Why This Pattern Matters:
DP is the most feared but most rewarding pattern. It optimizes recursive solutions by storing results of subproblems. While there are many DP patterns (1D, 2D, LIS, LCS, knapsack), the key is recognizing overlapping subproblems and optimal substructure. Master the mindset, not just individual problems.
When to Use:
- Optimization problems (max/min)
- Counting problems
- Decision making problems
- Problems with overlapping subproblems
- Keywords: "maximum", "minimum", "longest", "count ways"
Key Technique:
- Identify state variables
- Write recurrence relation
- Identify base cases
- Memoize or build bottom-up
Practice Problems:
- Climbing Stairs
- House Robber
- Longest Increasing Subsequence
- Longest Common Subsequence
- Coin Change
- Edit Distance
- Partition Equal Subset Sum
- Unique Paths
Related Posts
Check out my posts which may help you in your preparation :
- 13 DP Patterns for Interview Preparation
- 10 Dijkstra Variations for Interview Preparation
- Understanding Time Complexity: The 10^8 Operations Rule
- 10 Essential Design Problems for DSA Interviews
- Essential CS Fundamental Topics For Interviews
- Essential Graph Patterns for Coding Interviews
- Essential String Patterns for Coding Interviews
Good luck with your preparation! 🚀
Which pattern do you find most challenging? Drop a comment and let's discuss! 👇