24 DSA Patterns
24 DSA Patterns
io
Coding Interview Cheat Sheet
24 Coding
Interview
Patterns To
Land Your
Dream Job
Two Pointers
We can use two pointers (left and right) to traverse the
array, typically starting at different positions and move them
towards each other or in the same direction based on
specific conditions like matching characters or a sum.
n o o n
L R
n o o n
L R
Use when
Original Array
2 -1 3 -3 4
Prefix Sum
2 1 4 1 5
Use when
Asked for range sums or count
Want to reduce repeated O(n) work to O(1)
1 3 0 5 1 3 0 5
L R L R
Use when
Asked for longest/shortest subarray with a constrain
Fixed-size or variable-size window in array/string
problems
Start preparing for coding interviews with NeetCode 250 neetcode.io
Kadane’s Algorithm
Used to calculate the maximum sum subarray. Brings
the brute force O(n^2) complexity down to O(n).
Use when
Asked for maximum subarray sum
condition?”
1 5
1 2 3 1 5
1 2 3
# of subarrays with sum k
k=6
2 3 1
Use when
It uses two pointers - slow and fast. The fast pointer moves
twice as fast as the slow pointer.
fast
9 11
1 2 3 13
slow
17 15
Use when
5 Pre-order
Visit Order
2 9 First
Second
1 3 7 10
Third
In-order 5 5 Post-order
2 9 2 9
1 3 7 10 1 3 7 10
Use when
Traversing graphs/trees deepl
Asked to explore all paths, connected components, or
backtracking
1 1
2 2 3
3 4 5 6 7
Use when
1 1 1 0 0
row
2 0 0 0 1
3 0 1 0 0
A D "A": ["B"],
"C": ["E"],
B E "E": ["D"],
"D": []
Use when
"Is there a path from A to B?
Count the number of paths from source to destination
(DFS
Find the shortest path from node to target (BFS)
median.
The root of the max heap will always be <= than the root
of the min heap.
[1, 2, 3, 4, 5, 6]
3 4
1 2 5 6
Max Heap Min Heap
Median = 3 + 4 = 3.5
Use when
instead of an array.
P3
C2 P2 E2
C1 P1 E1
A1
Use when
Top K
1 5 11 9 7
(3)
9 11
Array
Use when
linked list.
1 2 3 4
4 3 2 1
Use when:
In this case, the answer and the base case is the leaf
nodes.
1 2 3
2 3 1 3 1 2
3 2 3 1 2 1
Use when
n=4
k=2
1 2 3 4
2 3 4 3 4 4
Use when
1
No Valid path
0 1
7 2 0
Use when
Need to combine BFS + state trackin
Need to use pruning
string a
A B C
0 0 0 0
A 0 1 1 1
string b D 0 1 1 1
C 0 1 1 2
D 0 1 2 2
Use when
Asked to find common subsequence, not substring
[ 2, 4, 6, 3, 8, 1]
6 8
4 4 3 3
2 2 2 2 2 1
Increasing Decreasing
Use when
cache[r][c]
20 10 4 1
10 6 3 1
4 3 2 1
1 1 1 1
Each calculated value
approach.
prevRow[0] 20 10 4 1
Discarded
from memory
problem
Use when:
a
b Overlap, but ‘b’ ends after ‘a’
a
b ‘b’ completely overlaps ‘a’
Use when: