A structured collection of Data Structures & Algorithms (DSA) patterns designed to help you recognize recurring problem-solving techniques instead of memorizing individual solutions.
The goal is simple:
Don't memorize solutions. Learn to recognize patterns.
Many DSA problems look different on the surface but use the same underlying technique.
For example:
- "Find a pair with a target sum"
- "Find two numbers satisfying a condition"
- "Find the longest substring satisfying a constraint"
- "Find the maximum sum subarray"
- "Find the minimum number of operations"
These problems often map to well-known patterns such as:
- Two Pointers
- Sliding Window
- Hashing
- Binary Search
- Prefix Sum
- Monotonic Stack
- Heap / Priority Queue
- Backtracking
- Dynamic Programming
- Graph Traversal
- Greedy Algorithms
Learning these patterns makes it easier to go from:
Problem β Identify Pattern β Choose Technique β Implement β Optimize
instead of:
Problem β Panic β Try Random Approaches β Get Stuck
When solving a problem, don't immediately start coding.
Ask:
- Array?
- String?
- Linked List?
- Tree?
- Graph?
- Matrix?
- Number?
- Search?
- Count?
- Optimize?
- Find all possibilities?
- Find maximum/minimum?
- Check existence?
- Construct an answer?
Constraints often tell you which algorithm is possible.
For example:
n <= 10
Brute force may be acceptable.
n <= 10^5
You probably need approximately:
O(n)
O(n log n)
Look for signals such as:
sorted array
substring
subarray
contiguous
frequency
top K
minimum/maximum
next greater
all combinations
shortest path
dependencies
These keywords often point toward a specific pattern.
Use hashing when you need:
- Fast lookup
- Frequency counting
- Duplicate detection
- Pair matching
- Grouping
- Prefix-state tracking
HashMap
HashSet
Dictionary
Set
Time: O(n)
Space: O(n)
- Two Sum
- Contains Duplicate
- Group Anagrams
- Longest Consecutive Sequence
- Subarray Sum Equals K
Commonly used when:
- Working with arrays or strings
- The input is sorted
- Searching for pairs
- Processing from both ends
- Maintaining two positions
left β
β right
Example:
while (left < right) {
if (condition) {
left++;
} else {
right--;
}
}Time: O(n)
Space: O(1)
- Two Sum II
- 3Sum
- Container With Most Water
- Valid Palindrome
- Remove Duplicates from Sorted Array
One of the most important patterns for array and string problems.
Look for:
- Subarray
- Substring
- Contiguous elements
- Longest
- Shortest
- At most K
- Exactly K
- Maximum/minimum within a range
left = 0
for right in range(n):
add nums[right]
while window_is_invalid:
remove nums[left]
left++
update answer
Time: O(n)
Space: O(k)
- Longest Substring Without Repeating Characters
- Maximum Length Substring With Two Occurrences
- Minimum Size Subarray Sum
- Longest Repeating Character Replacement
- Maximum Average Subarray
Use prefix sums when you need:
- Range sums
- Repeated subarray-sum queries
- Subarray sum conditions
- Cumulative information
Instead of repeatedly calculating:
nums[l] + nums[l+1] + ... + nums[r]
precompute:
prefix[i] = sum of elements before i
Then:
sum(l, r) = prefix[r + 1] - prefix[l]
Preprocessing: O(n)
Query: O(1)
Space: O(n)
Use binary search when:
- The array is sorted
- The search space is monotonic
- You need first/last occurrence
- You can eliminate half of the search space
left = 0
right = n - 1
while left <= right:
mid = left + (right - left) / 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
Time: O(log n)
Space: O(1)
Binary Search on Answer
Instead of searching an array, search the possible answer space.
Examples:
- Capacity To Ship Packages Within D Days
- Koko Eating Bananas
- Split Array Largest Sum
- Minimum Time to Complete Trips
Especially useful for linked lists.
Typical applications:
- Detect cycle
- Find middle node
- Find cycle entrance
- Compare positions moving at different speeds
slow = head
fast = head
while fast != null && fast.next != null:
slow = slow.next
fast = fast.next.next
- Linked List Cycle
- Linked List Cycle II
- Middle of the Linked List
- Happy Number
Use stacks when the problem involves:
- Matching parentheses
- Nested structures
- Undo operations
- Previous/next relationships
- Expression evaluation
- Valid Parentheses
- Min Stack
- Evaluate Reverse Polish Notation
- Daily Temperatures
- Remove All Adjacent Duplicates
A specialized stack pattern.
Look for:
Next greater
Next smaller
Previous greater
Previous smaller
Nearest greater
Nearest smaller
Maintain the stack in increasing or decreasing order.
Example:
while stack is not empty
and nums[stack.top] < nums[i]:
process stack.top
pop
- Daily Temperatures
- Next Greater Element
- Largest Rectangle in Histogram
- Online Stock Span
- Trapping Rain Water
Use BFS when processing things:
level by level
Typical applications:
- Shortest path in an unweighted graph
- Tree level-order traversal
- Minimum number of moves
- Grid traversal
queue.add(start)
while queue is not empty:
node = queue.remove()
for neighbor in neighbors(node):
if not visited:
visited.add(neighbor)
queue.add(neighbor)
Time: O(V + E)
Space: O(V)
Look for:
- Top K
- Kth largest/smallest
- Minimum/maximum repeatedly
- Scheduling
- Merging sorted collections
- Kth Largest Element
- Top K Frequent Elements
- Merge K Sorted Lists
- Find Median from Data Stream
- Task Scheduler
Usually:
Insert: O(log n)
Remove: O(log n)
Peek: O(1)
Look for:
- Intervals
- Meetings
- Start/end times
- Overlapping ranges
- Merging ranges
Sort by start time:
sort intervals by start
for each interval:
if overlapping:
merge
else:
create new interval
- Merge Intervals
- Insert Interval
- Non-overlapping Intervals
- Meeting Rooms
- Meeting Rooms II
A greedy solution makes the best local decision while building toward a global solution.
Look for:
maximum
minimum
earliest
latest
best immediate choice
Ask:
"Can I make the locally optimal choice without hurting the final answer?"
- Jump Game
- Gas Station
- Assign Cookies
- Activity Selection
- Partition Labels
Use backtracking when you need to explore:
- All combinations
- All permutations
- All subsets
- Decision trees
- Constraint-based possibilities
backtrack(state):
if solution:
add result
return
for choice in choices:
make choice
backtrack(new state)
undo choice
- Subsets
- Permutations
- Combination Sum
- N-Queens
- Sudoku Solver
- Word Search
Recursion is useful when the problem naturally breaks into smaller versions of itself.
Common structures:
Tree
Graph
Divide and conquer
Backtracking
Dynamic Programming
- What is the base case?
- What is the smaller problem?
- How do I combine the result?
Break a problem into smaller independent problems.
Problem
|
+--- Left
|
+--- Right
|
Combine
- Merge Sort
- Quick Sort
- Binary Search
- Maximum Subarray
O(n log n)
Dynamic Programming is one of the most important advanced DSA patterns.
Look for:
- Optimal answer
- Number of ways
- Minimum/maximum
- Repeated subproblems
- Choices at every step
- "Can we..." decisions
A problem usually has:
The same subproblems appear multiple times.
The optimal solution can be constructed from optimal solutions to smaller subproblems.
Recursion
+
Memoization
Tabulation
Ask:
1. What is the state?
2. What are the choices?
3. What is the transition?
4. What is the base case?
5. What is the final answer?
- 1D DP
- 2D DP
- Knapsack
- Subsequence DP
- String DP
- Interval DP
- Grid DP
- Partition DP
- Tree DP
- Bitmask DP
Graphs can represent:
Cities
Networks
Dependencies
Relationships
Connections
Paths
Two fundamental traversal techniques:
DFS
BFS
Useful for:
- Connected components
- Cycle detection
- Backtracking
- Topological traversal
- Exploring paths
Useful for:
- Shortest path in unweighted graphs
- Level-order exploration
- Minimum number of steps
Use topological sorting when the problem contains:
dependencies
prerequisites
ordering
tasks
courses
build systems
The graph must be a Directed Acyclic Graph (DAG).
Kahn's Algorithm
DFS
- Course Schedule
- Course Schedule II
- Alien Dictionary
- Build System Dependencies
Useful for:
- Connected components
- Dynamic connectivity
- Grouping
- Detecting cycles in undirected graphs
find(x)
union(x, y)
With:
Path Compression
+
Union by Rank/Size
the operations become extremely efficient.
Use a Trie for:
- Prefix searches
- Dictionary problems
- Autocomplete
- Word matching
- String prefixes
- Implement Trie
- Word Search II
- Design Add and Search Words
- Replace Words
AND &
OR |
XOR ^
NOT ~
LEFT SHIFT <<
RIGHT SHIFT >>
x ^ x = 0
x ^ 0 = x
- Single Number
- Counting Bits
- Power of Two
- Missing Number
- Subsets using Bitmasking
Common in:
- Islands
- Mazes
- Grid paths
- Connected components
- Flood fill
Typical directions:
up
down
left
right
Sometimes include diagonals:
top-left
top-right
bottom-left
bottom-right
- Number of Islands
- Flood Fill
- Rotting Oranges
- Pacific Atlantic Water Flow
- Word Search
| Problem Signal | Likely Pattern |
|---|---|
| Pair in sorted array | Two Pointers |
| Contiguous subarray | Sliding Window |
| Contiguous substring | Sliding Window |
| Frequency counting | HashMap |
| Fast lookup | HashSet / HashMap |
| Sorted search | Binary Search |
| First/last position | Binary Search |
| Next greater element | Monotonic Stack |
| Top K | Heap |
| Kth largest | Heap / Quickselect |
| Overlapping intervals | Intervals |
| All combinations | Backtracking |
| All permutations | Backtracking |
| All subsets | Backtracking / Bitmask |
| Minimum steps | BFS |
| Shortest unweighted path | BFS |
| Tree traversal | DFS / BFS |
| Dependencies | Topological Sort |
| Connected components | DFS / BFS / Union Find |
| Repeated subproblems | Dynamic Programming |
| Maximum/minimum with choices | DP / Greedy |
| Prefix matching | Trie |
| Connectivity | Union Find |
| Range sum | Prefix Sum |
| Next/previous greater | Monotonic Stack |
| Locally optimal choice | Greedy |
Use this process every time.
Explain the problem in your own words.
Don't code immediately.
Ask:
Array?
String?
Linked List?
Tree?
Graph?
Matrix?
Heap?
Estimate what complexity is required.
For example:
n <= 20
Possible:
O(2^n)
But:
n <= 100000
Usually requires something closer to:
O(n)
O(n log n)
Look for keywords.
substring β Sliding Window
sorted β Binary Search / Two Pointers
top K β Heap
next greater β Monotonic Stack
dependencies β Topological Sort
all possible β Backtracking
optimal value β DP / Greedy
Before optimizing, understand the straightforward solution.
Ask:
What would the simplest solution be?
Why is it too slow?
What repeated work can I eliminate?
This often reveals the optimized pattern.
| Complexity | Typical Use |
|---|---|
| O(1) | Direct access / calculation |
| O(log n) | Binary Search |
| O(n) | Hashing / Two Pointers / Sliding Window |
| O(n log n) | Sorting / Efficient divide & conquer |
| O(nΒ²) | Nested loops / 2D problems |
| O(2βΏ) | Subsets / Backtracking |
| O(n!) | Permutations |
| O(V + E) | Graph traversal |
dsa-patterns/
β
βββ README.md
β
βββ 01-hashing/
β βββ README.md
β βββ problems/
β
βββ 02-two-pointers/
β βββ README.md
β βββ problems/
β
βββ 03-sliding-window/
β βββ README.md
β βββ problems/
β
βββ 04-prefix-sum/
β βββ README.md
β βββ problems/
β
βββ 05-binary-search/
β βββ README.md
β βββ problems/
β
βββ 06-fast-slow-pointers/
β
βββ 07-stack/
β
βββ 08-monotonic-stack/
β
βββ 09-queue-bfs/
β
βββ 10-heap/
β
βββ 11-intervals/
β
βββ 12-greedy/
β
βββ 13-backtracking/
β
βββ 14-recursion/
β
βββ 15-divide-and-conquer/
β
βββ 16-dynamic-programming/
β
βββ 17-graphs/
β
βββ 18-topological-sort/
β
βββ 19-union-find/
β
βββ 20-trie/
β
βββ 21-bit-manipulation/
β
βββ 22-matrix/
Don't try to learn everything simultaneously.
1. Arrays
2. Strings
3. Hashing
4. Two Pointers
5. Sliding Window
6. Stack
7. Binary Search
8. Prefix Sum
9. Linked Lists
10. Fast & Slow Pointers
11. Heap
12. Intervals
13. Recursion
14. Trees
15. BFS
16. DFS
17. Backtracking
18. Greedy
19. Dynamic Programming
20. Graph Algorithms
21. Topological Sort
22. Union Find
23. Trie
24. Advanced DP
25. Bit Manipulation
For every problem, document your thinking using:
Problem
β
Understand
β
Constraints
β
Brute Force
β
Find Bottleneck
β
Recognize Pattern
β
Optimize
β
Implement
β
Analyze Complexity
β
Test Edge Cases
For each solved problem, maintain:
## Problem
What is being asked?
## Pattern
Which DSA pattern is being used?
## Intuition
Why does this pattern work?
## Approach
Step-by-step solution.
## Complexity
Time: O(?)
Space: O(?)
## Edge Cases
- Empty input
- Single element
- Duplicate values
- Maximum constraints
- Negative values
The goal of this repository is not to collect hundreds of solved problems.
The goal is to build the ability to look at a new problem and think:
"I have seen this structure before."
"This looks like Sliding Window."
"This is probably Binary Search on Answer."
"This is a Monotonic Stack problem."
"This is an optimization problem with overlapping subproblems."
"This looks like BFS because we need minimum steps."
That recognition is the real DSA skill.
Patterns are more valuable than solutions.
A single pattern can help solve dozens of problems.
A memorized solution usually helps solve only one.
Keep practicing:
Recognize β Reason β Implement β Optimize β Repeat
Part of the CodeWithIshwar learning ecosystem.
Recommended companion repositories:
leetcode-solutionsdsa-thinkingproblem-solving-notessystem-design-thinkingengineering-notes
Ishwar
Building in public as CodeWithIshwar.
Learn deeply. Solve consistently. Build publicly.
β If this repository helps you understand DSA patterns, consider starring the repository.