DSA Patterns Cheatsheet — 16 Core Algorithm Patterns | Interview Prep Buddy
Chalkboard Algorithmic Engine (39 Patterns)

DSA Pattern Blueprints & Visual Chalkboard

Recognize problem input signals, inspect step-by-step visual chalkboard diagrams, apply core tricks, and copy code blueprints!

👆
#1

Two Pointers

Use two index pointers to traverse a data structure (array, string, or linked list) from opposite ends or at different speeds.

Easy to Medium

🎯 Input Signals (When to use)

  • Input is a sorted array or string
  • Finding pairs, triplets, or sub-sequences matching a target sum/condition
  • In-place operations requiring O(1) extra memory (e.g. reversing array, removing duplicates)
  • Comparing characters from outer boundaries inward (e.g. Palindromes)

💡 Core Chalk Trick & Logic

Shrink or expand search space from both ends. If `sum < target`, move `left++` to increase value. If `sum > target`, move `right--` to decrease value.

Step-by-Step Chalkboard Diagram

✎ Chalkboard Sketch
  [ 1 ,  3 ,  5 ,  7 ,  11 ,  15 ]
    ↑                         ↑
   Left                     Right
   (sum = 16 > 12 -> move Right left ◄─)
   
  [ 1 ,  3 ,  5 ,  7 ,  11 ,  15 ]
    ↑                   ↑
   Left               Right
   (sum = 12 === 12 -> Target Found! ✓)

Common Pitfalls & Gotchas

  • Forgetting to check `left < right` loop termination condition
  • Not handling duplicate values when finding all unique triplets/quadruplets
  • Off-by-one errors on boundary indices
Time Complexity: O(N) single pass Space Complexity: O(1) extra space
🪟
#2

Sliding Window

Maintain a contiguous subarray/substring window that dynamically expands or shrinks based on problem constraints.

Medium
➕
#3

Prefix Sum & Hash Map

Store cumulative prefix sums in a Hash Map to find contiguous subarrays whose sum equals K or matches a target modulo/remainder in O(N) time.

Medium
🇳🇱
#4

Dutch National Flag (3-Way Partitioning)

Sort an array of 3 distinct values (e.g. 0s, 1s, and 2s) in a single pass in-place using 3 pointers (`low`, `mid`, `high`).

Medium
🗳️
#5

Boyer-Moore Majority Vote

Find the element that appears more than ⌊N/2⌋ times in an array in O(N) time and O(1) extra space.

Easy to Medium
✖️
#6

Product of Array Except Self (Prefix/Suffix Products)

Calculate an array `res` where `res[i]` is the product of all elements except `nums[i]` in O(N) time without using division.

Medium
🔄
#7

Array Reversal & Rotation Algorithm

Rotate an array by K steps or find the next lexicographical permutation by reversing sub-sections of the array in-place.

Medium
🐢
#8

Fast & Slow Pointers (Floyd's Cycle)

Use two pointers moving at different speeds (usually 1 step vs 2 steps) to detect cycles or find middle nodes in linked lists and arrays.

Easy to Medium
🔄
#9

Cyclic Sort

Sort an array of numbers in the range 1 to N in O(N) time and O(1) space by placing each number at its correct index (`nums[i] - 1`).

Easy to Medium
⛓️
#10

In-place Reversal of Linked List

Reverse pointers of a linked list in-place without creating new nodes using 3 tracking pointers: `prev`, `curr`, and `next`.

Easy to Medium
📅
#11

Merge Intervals

Sort overlapping intervals by start time, then merge adjacent intervals that overlap.

Medium
📈
#12

Kadane's Algorithm (Max Subarray Sum)

Find the maximum sum of a contiguous subarray in O(N) time using DP local vs global running sum.

Medium
↔️
#13

Expand Around Center (Palindromes)

Find palindromic substrings by expanding outward from each character (odd length) and pair of characters (even length).

Easy to Medium
🌐
#14

Tree Breadth-First Search (BFS)

Traverse a tree or graph level by level using a Queue (FIFO data structure).

Easy to Medium
🌲
#15

Tree Depth-First Search (DFS)

Traverse deep down a tree path before backtracking using Recursion or an explicit Stack.

Easy to Hard
🗺️
#16

Matrix Grid Traversal (Grid BFS/DFS)

Traverse a 2D grid/matrix using DFS or BFS with 4-directional or 8-directional cell movements.

Medium
🌊
#17

Multi-Source BFS

Start BFS queue with ALL source nodes simultaneously to find shortest distance transform or propagation time.

Medium
🧭
#18

Dijkstra's Algorithm (Shortest Path)

Find shortest distance from source node to all other nodes in a weighted graph with non-negative edge weights.

Medium to Hard
🌐
#19

Floyd-Warshall (All-Pairs Shortest Path)

Find shortest paths between ALL pairs of vertices in a weighted graph in O(V^3) time using 3D/2D DP.

Hard
📊
#20

Topological Sort (Kahn's Algorithm)

Order vertices of a Directed Acyclic Graph (DAG) such that for every directed edge u -> v, u comes before v.

Medium
🔗
#21

Disjoint Set Union (DSU / Union-Find)

Maintain a collection of disjoint sets, supporting near O(1) operations to find set representative and union two sets.

Medium
↩️
#22

Backtracking (Decision Tree)

Explore all possible combinations/permutations by building candidate solutions incrementally and undoing choices (backtracking) when a branch fails.

Medium to Hard
✂️
#23

Backtracking Duplicate Pruning

Prune redundant branch choices when input array contains duplicate values (e.g. Subsets II, Combination Sum II).

Medium
🧮
#24

Dynamic Programming (DP)

Break complex optimization/counting problems into overlapping subproblems, storing subproblem results to eliminate redundant computation.

Medium to Hard
🎒
#25

0/1 Knapsack Pattern

Choose a subset of items each with weight and value to maximize total value without exceeding capacity W (each item used at most ONCE).

Medium to Hard
🪙
#26

Unbounded Knapsack Pattern

Select items to reach a target sum or max value where items can be reused UNLIMITED times.

Medium
🔤
#27

Longest Common Subsequence (LCS)

Compare two strings `s1` and `s2` to find matching character sequences or transform distance.

Medium to Hard
📚
#28

Monotonic Stack / Queue

Maintain elements in stack/queue in strictly increasing or decreasing order to quickly find the Next Greater or Next Smaller Element.

Medium to Hard
⛰️
#29

Top K Elements (Heap / Priority Queue)

Keep track of the top K largest or smallest elements from an unsorted collection or stream.

Medium
🎯
#30

QuickSelect Pattern (K-th Element)

Find the K-th smallest/largest element in an unsorted array in average O(N) linear time using QuickSort partition logic.

Medium
🔀
#31

K-way Merge Pattern

Merge K sorted arrays or K sorted linked lists into a single sorted list using a Min-Heap of size K.

Hard
🌲
#32

Trie (Prefix Tree)

Tree structure storing characters at each node to enable fast string insertion, prefix lookup, and auto-complete.

Medium
🔤
#33

KMP String Search (LPS Prefix Function)

Search for pattern P in text T in O(N + M) time using Longest Proper Prefix which is also Suffix (LPS) array to avoid redundant comparisons.

Hard
🔠
#34

Character Frequency Map (Anagrams & Isomorphism)

Use a fixed-size frequency array of 26 integers or Hash Map to validate anagrams, isomorphic strings, and character distributions.

Easy to Medium
🔑
#35

Rabin-Karp Rolling Hash Algorithm

Use polynomial rolling hash to search for pattern P of length M in text T of length N in average O(N + M) time.

Hard
🗜️
#36

String Compression (Run-Length Encoding)

Compress consecutive identical characters in a string/array in-place by writing character followed by its frequency count.

Easy to Medium
🧮
#37

String Parsing Stack (Decode & Parentheses)

Use a Stack to parse nested string structures, parenthesized expressions, and multiplier strings like `3[a2[c]]`.

Medium
💡
#38

Bit Manipulation Tricks

Utilize bitwise operators (`&`, `|`, `^`, `~`, `<<`, `>>`) for fast constant-time arithmetic and boolean logic.

Easy to Medium
⚡
#39

Greedy Algorithms

Make the locally optimal choice at each step to reach a global optimum solution.

Medium