KEMBAR78
24 DSA Patterns | PDF | Applied Mathematics | Computer Programming
0% found this document useful (0 votes)
43 views26 pages

24 DSA Patterns

Uploaded by

gourav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views26 pages

24 DSA Patterns

Uploaded by

gourav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

neetcode.

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.

This allows for one pass and O(n) time.

n o o n
L R

n o o n
L R
Use when

Asked to find pairs, remove duplicates, or merg


Move inward or scan with left/right


Start preparing for coding interviews with NeetCode 250 neetcode.io


Prefix Sums
A prefix sum is a technique used to calculate the running
sum of the array up until a given index.

It’s useful when we are asked to retrieve a range sum query


or a subarray where sum equals k.

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)


Start preparing for coding interviews with NeetCode 250 neetcode.io


Sliding Window
Uses a left and a right pointer to expand the window
by adding elements from the right until a given
constraint is violated.

Once the constraint is broken, it removes elements


from the left to start a new window.


The window can be of a fixed or variable size.
Fixed Variable
1 3 0 5 1 3 0 5
L R L R

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).

It iterates through the array, maintains a running sum,


resets it to 0 if it becomes negative and updates the
maximum sum as needed.
n
Initial State 4 2
curSum = 4
-1 -7 3 4
maxSum = 4
n
curSum = -2
Reset to Zero 4 -1 2 -7 3 4
maxSum = 5
n
curSum = 7
Final State 4 -1 2 -7 3 4
maxSum = 7

Use when
Asked for maximum subarray sum

Start preparing for coding interviews with NeetCode 250 neetcode.io


Find number of 

subarrays
Frequently tested, blends in sliding window, prefix

sum, hashing, and even two-pointer techniques.

It’s asking: “How many subarrays meet a certain

condition?”

1 5

1 2 3 1 5
1 2 3
# of subarrays with sum k

k=6
2 3 1

Use when

How many subarrays have sum exactly k


How many subarrays have at most k distinct
elements
How many subarrays are strictly increasing
How many subarrays have product less than k?

Start preparing for coding interviews with NeetCode 250 neetcode.io


Fast and Slow Pointers

Also called Floyd’s Tortoise and Hare algorithm.

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

Linked lists: detecting cycles, middle node, palindrom


“Loop detection” or “infinite loop” scenarios

Start preparing for coding interviews with NeetCode 250 neetcode.io


Depth-First Search
Prioritizes visiting nodes depth-first. Three orders:

Preorder: root → left subtree → right subtree

Inorder: left subtree → root → right subtree

Postorder: left subtree → right subtree → root

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

Start preparing for coding interviews with NeetCode 250 neetcode.io


Breadth-First Search
Prioritizes breadth-first when traversing the tree.

Also known as level order traversal, you visit all the


nodes in one level before moving on to the next.

1 1

2 2 3

3 4 5 6 7

Use when

Shortest path in unweighted graph/gri


Layer-by-layer or time-based spread

Start preparing for coding interviews with NeetCode 250 neetcode.io


Matrix Traversal
This format will be given as a 2D matrix and each square
will represent a vertex.

The problem statement will tell you the rules of the


traversal.
col
0 1 2 3
0 0 0 0 0

1 1 1 0 0
row
2 0 0 0 1

3 0 1 0 0

Vertex can be reached


Use when
2D problems: search, flood fill, island count, rotatio
Recognize when directions like up/down/left/right
matter

Start preparing for coding interviews with NeetCode 250 neetcode.io


Adjacency List BFS /
DFS
Adjacency List is one way to represent a graph. It
maps vertices to its neighbors.

A D "A": ["B"],

"B": ["C", "E"],

"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)

Start preparing for coding interviews with NeetCode 250 neetcode.io


Two Heaps
On the harder side of problems, typically used

when finding a median, such as the sliding window

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

Median from data strea


Asked to balance two sides or get min from max half

Start preparing for coding interviews with NeetCode 250 neetcode.io


Binary Search
(Modified)
Perform binary search on a range of elements,

instead of an array.

The array doesn’t matter — the constraint does




Think: “What’s the smallest/largest value 

that works?

Start preparing for coding interviews with NeetCode 250 neetcode.io


Topological Sort
A way to arrange items with dependencies in an order that
satisfies all the dependencies. It's applicable only to
Directed Acyclic Graphs (DAGs) because cycles would make
it impossible to create a valid ordering.

P3

C2 P2 E2

C1 P1 E1

A1
Use when

Tasks with dependencies, course schedulin


"Can we complete all tasks?" or "Order of execution"


Start preparing for coding interviews with NeetCode 250 neetcode.io


Top K

Used in problems where we are asked to find

the “top k”, as defined by the problem.

Create a max hea

Push elements on the heap while heap.size <=

Pop elements when the size exceeds k

Due to the nature of this, pop will remove the

worst elements and only keep the best elements.

Top K

1 5 11 9 7

(3)

9 11
Array

Use when

Asked for largest/smallest k item

Often used with min/max heaps

Start preparing for coding interviews with NeetCode 250 neetcode.io


Linked List Reversal
Refers to completely reversing the pointers of the

linked list.

1 2 3 4

4 3 2 1

Use when:

- Reverse a linked list in-place



- Used in palindrome check, group k reversal, etc.

Start preparing for coding interviews with NeetCode 250 neetcode.io


Permutations
A permutation is a unique arrangement of all the numbers
in nums, where order matters and no duplicates are
allowed.

For example, [1,2,3] and [1,3,2] are two distinct


permutations of [1,2,3].

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

“Generate all possible orders” or arrangement


Order matters, no repetition

Start preparing for coding interviews with NeetCode 250 neetcode.io


Combinations
We’re given a range, [1,n] and asked to produce all possible
combinations of length k.

Similar to generating subsets, but the depth of our


backtracking tree is limited to k, ensuring that each
combination contains exactly k elements.

We explore all paths and backtrack to find other


combinations once the size of the tree becomes k.

n=4

k=2

1 2 3 4

2 3 4 3 4 4

[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]

Use when

“Pick k items” or subsets where order doesn’t matter

Start preparing for coding interviews with NeetCode 250 neetcode.io


Tree Maze (Backtracking)

We are trapped in a maze and trying to find our way out.

We can try all possible paths until we find the

correct one. If we hit a dead-end, we backtrack and try


another path.

1
No Valid path
0 1

7 2 0

0 Valid path exists

Use when
Need to combine BFS + state trackin
Need to use pruning

Start preparing for coding interviews with NeetCode 250 neetcode.io


Longest Common
Subsequence
The longest subsequence common to all sequences in a
set of sequences (often just two sequences).

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


Start preparing for coding interviews with NeetCode 250 neetcode.io


Monotonic Stack

Monotonic stack is a stack that maintains its elements in

increasing or decreasing order.

[ 2, 4, 6, 3, 8, 1]

6 8

4 4 3 3

2 2 2 2 2 1

Increasing Decreasing

Use when

Find next/previous greater/smaller elemen

Histogram problems, daily temperatures, boundaries

Start preparing for coding interviews with NeetCode 250 neetcode.io


Memoization
Refers to a dynamic programming technique where you
start from the final problem and recursively

break it into smaller subproblems.

cache[r][c]

20 10 4 1
10 6 3 1
4 3 2 1
1 1 1 1
Each calculated value

is stored in the cache to avoid recalculation

- Recursive solution with overlapping subproblems



- High time complexity unless optimized

Start preparing for coding interviews with NeetCode 250 neetcode.io


Tabulation

Sometimes referred to as the true dynamic programming

approach.

It builds the solution from the base case all the

way up to the final solution.

prevRow[0] 20 10 4 1

Discarded

from memory

We only need the previous row’s values,

so discard every other row

- Build solution bottom-up via a table


- Used when order of solving subproblems is known

Start preparing for coding interviews with NeetCode 250 neetcode.io


Multi-Source BFS

A variation of the classic Breadth-First Search, but

instead of starting from one node, it starts from

multiple sources simultaneously.

Classic rotting oranges

problem

Use when:


- Multiple starting points spreading in parallel


- "Minimum time to infect/reach" type problems

Start preparing for coding interviews with NeetCode 250 neetcode.io


Merge Intervals
You are given intervals and asked to:


- Merge overlapping intervals

- Insert a new interval

- Check for overlaps and conflicts

a b ‘a’ and ‘b’ do not overlap

a
b Overlap, but ‘b’ ends after ‘a’

a ‘a’ completely overlaps ‘b’


b
a Overlap, but ‘a’ ends after ‘b’
b

a
b ‘b’ completely overlaps ‘a’

Use when:


- Given ranges/intervals and need to merge, insert, or find


gaps

- "Can we attend all meetings?" or "What's the union?"

Start preparing for coding interviews with NeetCode 250 neetcode.io


Join 1,000,000+ People
Preparing for Coding
Interviews
neetcode.io

You might also like