DSA patterns: 14 patterns that solve 80% of problems
Recognise the pattern from the question, then apply the template.
How to use this guide
80% of coding interview questions are built from a small set of patterns. Learn how to spot each one from the question's wording, see the template with a real example and its output, then solve the practice problem (answer hidden).
Before writing any code, finish this sentence: "This looks like ___ because the question says ___." That one habit doubles your speed.
1. Hashing (dictionary / set)
Definition: A hash table is a data structure that stores keyβvalue pairs and uses a hash function to compute an index into an array of buckets, giving average O(1) insert, lookup and delete.
How it works: The hash function maps a key to a bucket; collisions (two keys in one bucket) are handled by chaining or open addressing. Performance degrades to O(n) in the worst case, so good hash functions and resizing matter.
Example: Python dict, Java HashMap: checking "[email protected]" in seen is instant.
π§ In simple words
Spot it: "find a pair", "count", "duplicates", "first unique", "seen before".
Checking if a username is taken β a set answers "seen before?" instantly instead of scanning every user.
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
print(two_sum([2, 7, 11, 15], 9))[0, 1]
Practice: return True if any value appears twice.
Show answer
def has_dup(a): return len(set(a)) != len(a)
print(has_dup([1, 2, 3, 1]), has_dup([1, 2, 3]))True False
2. Two pointers
Definition: The two-pointer technique uses two indices that move through a sequence (from both ends or at different speeds) to solve a problem in one pass.
How it works: Common on sorted arrays: move the left pointer right when the sum is too small and the right pointer left when it is too large, giving O(n) instead of O(nΒ²). Fast/slow pointers detect cycles in linked lists.
Example: Checking whether a string is a palindrome by comparing characters from both ends.
π§ In simple words
Spot it: sorted array, "pair with sum", palindrome, "remove duplicates in place".
def is_palindrome(s):
s = [c.lower() for c in s if c.isalnum()]
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]: return False
i, j = i + 1, j - 1
return True
print(is_palindrome("A man, a plan, a canal: Panama"))True
3. Sliding window
Definition: A sliding window is a sub-range of an array or string that moves across the data while maintaining some aggregate (sum, count, set of characters), so each element is processed a constant number of times.
How it works: Fixed-size windows add the new element and remove the outgoing one. Variable-size windows expand the right edge and shrink the left edge while a condition is violated. Time O(n).
Example: Longest substring without repeating characters; maximum sum of any 3 consecutive days.
π§ In simple words
Spot it: "longest / shortest / maximum substring or subarray with a condition".
"Best 7-day sales streak" β slide a 7-day window across the year instead of recalculating each week from scratch.
def max_sum_k(a, k):
s = best = sum(a[:k])
for i in range(k, len(a)):
s += a[i] - a[i - k]
best = max(best, s)
return best
print(max_sum_k([2, 1, 5, 1, 3, 2], 3))9
4. Stack
Definition: A stack is a linear data structure that follows LIFO (Last In, First Out): elements are added (push) and removed (pop) only at the top.
How it works: Push, pop and peek are O(1). Used for function calls (the call stack), undo, expression evaluation, bracket matching and the "next greater element" pattern (monotonic stack).
Example: Browser back button: the last page you visited is the first one you go back to.
π§ In simple words
Spot it: brackets, "next greater element", undo, evaluate expressions.
def valid(s):
pair, st = {")": "(", "]": "[", "}": "{"}, []
for ch in s:
if ch in pair:
if not st or st.pop() != pair[ch]: return False
else: st.append(ch)
return not st
print(valid("{[()]}"), valid("([)]"))True False
5. Binary search
Definition: Binary search is an algorithm that finds a target in a sorted collection by repeatedly halving the search interval.
How it works: Compare with the middle element; discard the half that can't contain the target. Time O(log n). It also works on any monotonic condition ("find the smallest x for which f(x) is true").
Example: Finding a word in a dictionary by opening the middle page and moving left or right.
π§ In simple words
Spot it: sorted data, or "minimum/maximum value that satisfies a condition".
def search(a, t):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == t: return mid
if a[mid] < t: lo = mid + 1
else: hi = mid - 1
return -1
print(search([1, 3, 5, 7, 9, 11], 7))3
Using while lo < hi with hi = mid - 1 β mixing the two templates causes infinite loops or skipped answers. Pick one template and stick to it.
6. Linked list (fast & slow pointers)
Definition: A linked list is a linear data structure in which each element (node) stores a value and a reference to the next node (and in a doubly linked list, also the previous node).
How it works: Insertion/deletion at a known node is O(1), but access by index is O(n) because you must walk from the head. No contiguous memory is needed.
Example: A music playlist where each song points to the next.
π§ In simple words
Spot it: "middle of list", "cycle", "reverse".
class Node:
def __init__(s, v, n=None): s.v, s.n = v, n
def middle(h):
slow = fast = h
while fast and fast.n: slow, fast = slow.n, fast.n.n
return slow.v
lst = Node(1, Node(2, Node(3, Node(4, Node(5)))))
print(middle(lst))3
7. Trees β DFS and BFS
Definition: A tree is a hierarchical data structure of nodes connected by edges with one root and no cycles; a binary tree allows at most two children per node. DFS (depth-first search) explores as deep as possible before backtracking; BFS (breadth-first search) explores level by level.
How it works: DFS uses recursion or a stack (pre-order, in-order, post-order traversals). BFS uses a queue. A binary search tree keeps left < node < right, giving O(log n) search when balanced.
Example: A company org chart; BFS lists employees level by level, DFS follows one reporting line to the bottom.
π§ In simple words
Spot it: any parent/child structure; "depth", "level order", "path sum".
class T:
def __init__(s, v, l=None, r=None): s.v, s.l, s.r = v, l, r
def depth(t): return 0 if not t else 1 + max(depth(t.l), depth(t.r))
root = T(1, T(2, T(4)), T(3))
print(depth(root))3
8. Heap (top K)
Definition: A heap is a complete binary tree that satisfies the heap property β every parent is β€ its children (min-heap) or β₯ them (max-heap) β usually stored in an array.
How it works: Get the min/max in O(1); insert and remove in O(log n). A priority queue is the abstract type a heap implements. Building a heap from n items is O(n).
Example: Top-K problems: keep a min-heap of size K to find the 10 highest-rated restaurants.
π§ In simple words
Spot it: "top K", "K largest/smallest", "K closest".
import heapq
print(heapq.nlargest(3, [5, 1, 9, 3, 7, 8]))[9, 8, 7]
9. Backtracking
Definition: Backtracking is an algorithmic technique that builds a solution step by step and abandons ("backtracks" from) a partial solution as soon as it cannot lead to a valid answer.
How it works: It explores a decision tree with recursion: choose β explore β un-choose. Pruning invalid branches early keeps it practical. Typical complexity is exponential.
Example: Generating all subsets, permutations, N-Queens, Sudoku.
π§ In simple words
Spot it: "all combinations / subsets / permutations".
def subsets(a):
out = [[]]
for x in a: out += [s + [x] for s in out]
return out
print(subsets([1, 2, 3]))[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
10. Graphs (BFS / DFS on a grid)
Definition: A graph is a set of vertices (nodes) connected by edges, which can be directed or undirected and weighted or unweighted.
How it works: Stored as an adjacency list or matrix. Traversed with BFS/DFS; shortest paths with BFS (unweighted) or Dijkstra (weighted); ordering dependencies with topological sort.
Example: Cities and roads; course prerequisites; friends in a social network.
π§ In simple words
Spot it: islands, shortest path in a grid, prerequisites.
def islands(g):
R, C, n = len(g), len(g[0]), 0
def sink(r, c):
if 0 <= r < R and 0 <= c < C and g[r][c] == "1":
g[r][c] = "0"
for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)): sink(r+dr, c+dc)
for r in range(R):
for c in range(C):
if g[r][c] == "1": n += 1; sink(r, c)
return n
print(islands([list("11000"), list("11000"), list("00100"), list("00011")]))3
11. Dynamic programming
Definition: Dynamic programming solves a problem by breaking it into overlapping subproblems, solving each subproblem once and storing its result.
How it works: It applies when a problem has optimal substructure and overlapping subproblems. Memoisation = top-down recursion with a cache; tabulation = bottom-up filling of a table. Define the state, the transition (recurrence) and the base cases.
Example: Ways to climb n stairs = ways(nβ1) + ways(nβ2), computed once per n.
π§ In simple words
Spot it: "number of ways", "minimum cost", "maximum profit", choices that overlap.
Climbing stairs taking 1 or 2 steps: ways(n) = ways(nβ1) + ways(nβ2) β the same small answers are reused, so store them.
def climb(n):
a, b = 1, 1
for _ in range(n): a, b = b, a + b
return a
print([climb(i) for i in range(1, 8)])[1, 2, 3, 5, 8, 13, 21]
12. Greedy & intervals
Definition: A greedy algorithm builds a solution by always making the choice that looks best at the moment, without revisiting earlier choices.
How it works: It's correct only when the problem has the greedy-choice property (a local optimum leads to a global optimum) β proven by exchange arguments. Usually preceded by sorting.
Example: Scheduling the maximum number of meetings by always picking the one that ends earliest.
π§ In simple words
Spot it: meetings, merge ranges, "minimum number of β¦".
def merge(iv):
iv.sort(); out = [iv[0]]
for s, e in iv[1:]:
if s <= out[-1][1]: out[-1][1] = max(out[-1][1], e)
else: out.append([s, e])
return out
print(merge([[1, 3], [2, 6], [8, 10], [15, 18]]))[[1, 6], [8, 10], [15, 18]]
13. Prefix sums
Spot it: "sum of a range" asked many times, "subarray sum equals K".
a = [3, 1, 4, 1, 5]
pre = [0]
for x in a: pre.append(pre[-1] + x)
print(pre[4] - pre[1]) # sum of a[1..3]6
14. Bit manipulation
Spot it: "single number", powers of two, toggling flags.
from functools import reduce
print(reduce(lambda x, y: x ^ y, [4, 1, 2, 1, 2])) # x ^ x = 04
15. Your 30-day pattern plan
| Days | Patterns |
|---|---|
| 1β4 | Hashing, two pointers |
| 5β8 | Sliding window, stack |
| 9β11 | Binary search, prefix sums |
| 12β15 | Linked list, trees |
| 16β18 | Heap, backtracking |
| 19β22 | Graphs |
| 23β27 | Dynamic programming |
| 28β30 | Greedy, bits + 2 timed mock interviews |