Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Guides › DSA

12 DSA Patterns That Solve Most Interview Questions

Two pointers, sliding window, binary search on answer, BFS/DFS, DP and more — how to recognise each pattern from the question and a template for each.

Interview problems look endless, but most of them are built from about a dozen patterns. Once you can recognise the pattern from the question, the problem is half solved. For each pattern below you get the signal (words in the question that point to it), the idea, and a short template.

1. Two pointers

Signal: sorted array, pair or triplet with a target sum, remove duplicates in place, palindrome check.

Keep one pointer at each end (or both at the start) and move them based on a comparison, turning O(n²) pair checks into O(n).

i, j = 0, len(a) - 1
while i < j:
    s = a[i] + a[j]
    if s == target: return (i, j)
    if s < target: i += 1
    else: j -= 1

Classic problems: pair sum in sorted array, 3Sum, container with most water.

2. Sliding window

Signal: "subarray" or "substring" that is contiguous, with a condition like "at most K distinct", "sum ≤ X", "longest/shortest".

Grow the window on the right; shrink from the left while the condition is broken.

left = 0
for right in range(len(s)):
    add(s[right])
    while broken():
        remove(s[left]); left += 1
    best = max(best, right - left + 1)

Classic problems: longest substring without repeating characters, max sum subarray of size K, minimum window substring.

3. Prefix sums

Signal: many range-sum queries, "subarray sum equals K", balance of 0s and 1s.

prefix[i] stores the sum of the first i elements, so any range sum is prefix[r+1] - prefix[l] in O(1). Combine with a hash map to count subarrays with sum K.

4. Hashing

Signal: "have I seen this before?", frequency, duplicates, two-sum on an unsorted array, grouping anagrams.

Trade memory for speed: a set or map gives O(1) average lookups. When your brute force has an inner loop that searches for something, a hash map usually removes it.

5. Binary search (including on the answer)

Signal: sorted data, "minimum possible maximum", "smallest X such that…", very large ranges (10⁹).

If you can write a function ok(x) that is false, false, …, true, true, binary search finds the first true in O(log range).

lo, hi = low, high
while lo < hi:
    mid = (lo + hi) // 2
    if ok(mid): hi = mid
    else: lo = mid + 1

Classic problems: search in rotated array, Koko eating bananas, allocate minimum pages, aggressive cows.

6. Fast and slow pointers

Signal: linked list cycle, middle of a list, "happy number", duplicate number in an array of 1..n.

One pointer moves one step, the other two steps. If there is a cycle, they meet.

7. Monotonic stack

Signal: "next greater element", "previous smaller", stock span, largest rectangle in a histogram, daily temperatures.

Keep a stack whose values are always increasing (or decreasing). Each element is pushed and popped once, so the whole pass is O(n).

8. Heap / top-K

Signal: "K largest", "K most frequent", "K closest", merge K sorted lists, running median.

Keep a heap of size K. Each insert costs O(log K), so the total is O(n log K) instead of sorting everything.

9. Tree DFS

Signal: almost any binary tree problem — height, diameter, path sum, balanced check, lowest common ancestor.

Ask: what does each child need to return to its parent? Write the recursion around that answer.

def dfs(node):
    if not node: return 0
    l, r = dfs(node.left), dfs(node.right)
    # combine l and r, maybe update a global answer
    return 1 + max(l, r)

10. BFS (level order and shortest path)

Signal: level-by-level traversal, "minimum number of steps/moves", shortest path in an unweighted grid or graph, rotting oranges, word ladder.

BFS explores in rings, so the first time you reach a node is via the shortest path. Use a queue and a visited set.

11. Graph DFS, union–find and topological sort

Signal: connected components, number of islands, cycle detection, "can all courses be finished", dependency order.

12. Dynamic programming

Signal: "number of ways", "minimum/maximum cost", "can we reach", choices at each step, and a brute-force recursion that repeats the same sub-problems.

The reliable recipe:

  1. Write the recursive brute force and define the state (what parameters describe a sub-problem).
  2. Add memoisation — store each state's answer.
  3. If needed, convert to a bottom-up table and optimise space.

Classic families: 1D (climbing stairs, house robber), grid paths, knapsack (subset sum, coin change), strings (LCS, edit distance), and longest increasing subsequence.

How to practise patterns

Don't practise randomly. Pick one pattern, solve 5–8 problems of it in a row until the signal is obvious, then move on. After every 3 patterns, do a mixed set where you don't know the pattern in advance — that is what interviews feel like.

The Codify DSA Sheet is grouped by topic for focused practice, and the weekly contests give you the mixed, timed version. Between contests, a Code Battle gives you a single unseen problem against another coder — a quick way to test pattern recognition under time pressure. If a pattern doesn't click, watch it step by step in the Visualizer, or revise the worked notes on two pointers, sliding window, binary search, backtracking and dynamic programming. New to DSA? Start with how to start DSA from zero.

More guides