5 DSA Patterns Every Student Must Know Before a Coding Interview
TL;DR: Interviewers reuse problem shapes. Learn two pointers, sliding window, hash maps, BFS/DFS, and 1-D dynamic programming — in that order of comfort — and you'll recognize most questions within the first minute of reading them. Each pattern below comes with a runnable example you can execute and modify in Cubemate.
Interview problems feel infinite when you practice them randomly. They stop feeling infinite the day you notice that "find two numbers that sum to a target", "container with most water", and "remove duplicates from sorted array" are the same idea wearing different clothes.
That idea is a pattern. Here are the five with the best effort-to-coverage ratio.
1. Two pointers
When to reach for it: the input is sorted (or can be sorted), and you're looking for a pair, a triplet, or a partition.
Instead of checking every pair — O(n²) — you place one pointer at each end and walk them toward each other, discarding half the search space at every step.
def two_sum_sorted(nums, target):
left, right = 0, len(nums) - 1
while left < right:
current = nums[left] + nums[right]
if current == target:
return [left, right]
if current < target:
left += 1 # need a bigger sum
else:
right -= 1 # need a smaller sum
return []
print(two_sum_sorted([2, 7, 11, 15, 21], 26)) # [2, 3]
Classic problems: Two Sum II, 3Sum, Valid Palindrome, Container With Most Water.
2. Sliding window
When to reach for it: the question mentions a contiguous subarray or substring — "longest substring without repeating characters", "maximum sum of any window of size k".
You maintain a window over the data and slide it forward, updating your answer incrementally instead of recomputing from scratch.
def longest_unique_substring(s):
seen = {}
start = best = 0
for end, char in enumerate(s):
if char in seen and seen[char] >= start:
start = seen[char] + 1 # shrink window past the repeat
seen[char] = end
best = max(best, end - start + 1)
return best
print(longest_unique_substring("abcabcbb")) # 3 ("abc")
Classic problems: Longest Substring Without Repeating Characters, Minimum Window Substring, Max Consecutive Ones III.
3. Hash maps
When to reach for it: you're about to write a nested loop that searches for "have I seen this before?" — a hash map answers that question in O(1) and turns O(n²) into O(n).
This is the single most common optimization in interviews, and it's also the first pattern worth learning because it requires no setup beyond a dictionary.
def first_non_repeating(s):
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
for i, char in enumerate(s):
if counts[char] == 1:
return i
return -1
print(first_non_repeating("interview")) # 0 ('i'... wait, run it and check!)
Run that last example. The answer might surprise you — i appears twice in "interview". Catching your own wrong assumptions by executing code is exactly the habit that separates candidates who pass from candidates who freeze.
Classic problems: Two Sum, Group Anagrams, Longest Consecutive Sequence, Ransom Note.
4. BFS and DFS
When to reach for it: the data is a tree, a graph, a grid, or anything where you "explore neighbors" — islands in a matrix, shortest path, course prerequisites.
- BFS (queue) explores level by level → use it for shortest path questions.
- DFS (recursion or stack) dives deep first → use it for connectivity and exhaustive exploration.
from collections import deque
def num_islands(grid):
rows, cols = len(grid), len(grid[0])
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
islands += 1
queue = deque([(r, c)])
grid[r][c] = "0"
while queue: # BFS flood-fill
x, y = queue.popleft()
for dx, dy in ((1,0),(-1,0),(0,1),(0,-1)):
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == "1":
grid[nx][ny] = "0"
queue.append((nx, ny))
return islands
grid = [["1","1","0","0"],
["1","0","0","1"],
["0","0","1","1"]]
print(num_islands(grid)) # 3
Classic problems: Number of Islands, Binary Tree Level Order Traversal, Course Schedule, Word Ladder.
5. Dynamic programming (start with 1-D)
When to reach for it: the problem asks for a maximum, minimum, or count of ways, and the answer for input n can be built from answers to smaller inputs.
Don't start with 2-D grid DP. Start with 1-D problems where the recurrence is one line:
def climb_stairs(n):
# ways(n) = ways(n-1) + ways(n-2) — same recurrence as Fibonacci
a, b = 1, 1
for _ in range(n - 1):
a, b = b, a + b
return b
for steps in [2, 3, 5, 10]:
print(f"{steps} steps -> {climb_stairs(steps)} ways")
Classic problems: Climbing Stairs, House Robber, Coin Change, Maximum Subarray (Kadane's algorithm).
How to practice so the patterns actually stick
- Group your practice by pattern, not by random problem lists. Solve 5–10 problems per pattern before moving on.
- Execute everything. Reading a solution creates familiarity; running it against your own test cases creates understanding. Every example above runs as-is in Cubemate's cloud sandbox — no local setup.
- Explain the pattern out loud before coding, the way you would in a real interview: "this asks about a contiguous substring, so I'll use a sliding window with a hash map for the last-seen index."
- Go deep with a tutorial when a pattern won't click. Ask Bookmate for "a chapter-by-chapter tutorial on sliding window problems in Python" and you'll get a book-style walkthrough where every example is runnable.
Five patterns won't cover every question — heaps, backtracking, and binary search on answers show up too. But these five carry the most weight per hour of practice, and they're the foundation the others build on.
Frequently asked questions
How many DSA patterns do I need to learn for coding interviews?
Roughly 12 to 15 named patterns exist, but five of them — two pointers, sliding window, hash maps, BFS/DFS, and dynamic programming — cover the majority of questions asked at most companies. Start with these five before going wider.
What is the fastest way to practice DSA patterns?
Solve 5 to 10 problems per pattern rather than random problems. Grouping by pattern trains you to recognize the shape of a problem, which is the skill interviews actually test. Running your solutions against real inputs, not just reading them, is what makes the pattern stick.
Which DSA pattern should a beginner learn first?
Hash maps, then two pointers. Hash map problems teach you to trade memory for speed, and two pointers teaches you to reason about sorted data — both appear constantly and need no advanced prerequisites.
Can I practice DSA in the browser without setting up a coding environment?
Yes. Cubemate runs Python, Java, C++, Go, Rust, and JavaScript in a cloud sandbox, so you can write and execute interview solutions from any browser with zero installation.
Ready to start coding?
Write, run, and learn code in your browser — Python, Java, Go, Rust and more. No installation, no setup. Free 7-day trial.
Start Free