Cloudvyn AIAI Interview Platform for freshers in India on cloudvyn
Cloudvyn

15 Most Asked DSA Patterns in Coding Interviews (2026 Guide)

A
Abhishek madoliya
·21 Aug 2026·12 min read
Most Asked DSA Patterns

If you've ever solved 300+ LeetCode problems and still frozen in an interview, you already know the truth: grinding random problems doesn't make you interview-ready — recognizing patterns does.

Every coding interview question, no matter how "unique" it looks, is almost always a disguised version of a well-known pattern. Interviewers at Google, Amazon, Microsoft, and fast-growing startups don't invent a new algorithm for every question — they reuse the same 15–20 underlying techniques and change the story around them.

This guide breaks down the most frequently asked DSA patterns in coding interviews, why they show up so often, when to use each one, and the classic problems that test them — so you can walk into your next interview recognizing the pattern in the first 60 seconds instead of the last 5 minutes.

Why Learning Patterns Beats Memorizing Solutions

There are over 3,000 problems on LeetCode alone. No one has time to memorize each one — and interviewers know that. What they're actually testing is whether you can map an unseen problem to a known technique and reason about trade-offs out loud.

Data from companies like AlgoMonster and pattern-tracking sites consistently shows the same thing: a small set of core patterns — Two Pointers, Sliding Window, Trees/Graphs (BFS/DFS), Dynamic Programming, and Heaps — account for the overwhelming majority of questions asked across FAANG and mid-size tech companies. Company-specific breakdowns (Uber, TikTok, Oracle, Snowflake, PayPal) each lean on the same core 12–20 patterns, just with a different mix of arrays, graphs, or DP depending on the team.

The practical implication: study depth over breadth. Fifteen well-understood patterns will take you further than 300 memorized solutions.


1. Two Pointers

What it is: Two indices traverse a data structure — either moving toward each other, moving in the same direction, or one moving faster than the other.

When to use it: Sorted arrays, palindrome checks, pair-sum problems, removing duplicates in place, or merging two sorted structures.

Time complexity: Usually O(n), down from a brute-force O(n²).

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]
        elif current < target:
            left += 1
        else:
            right -= 1
    return []

Classic problems: Two Sum II (sorted), 3Sum, Container With Most Water, Valid Palindrome, Remove Duplicates from Sorted Array, Trapping Rain Water.

Common mistake: Using two pointers on an unsorted array without first checking whether sorting is even allowed (it changes the original indices).


2. Sliding Window

What it is: A "window" (subarray/substring) expands and contracts over the data instead of restarting from scratch for every possible subarray — turning an O(n²) or O(n³) brute force into O(n).

When to use it: Any problem involving a contiguous subarray or substring — max/min sum, longest/shortest substring with a condition, or counting subarrays that meet a constraint.

Two flavors:

  • Fixed size window — e.g., max sum of every subarray of size k.

  • Variable size window — e.g., longest substring without repeating characters, minimum window substring.

def longest_unique_substring(s):
    seen = {}
    left = max_len = 0
    for right, char in enumerate(s):
        if char in seen and seen[char] >= left:
            left = seen[char] + 1
        seen[char] = right
        max_len = max(max_len, right - left + 1)
    return max_len

Classic problems: Longest Substring Without Repeating Characters, Minimum Window Substring, Sliding Window Maximum, Find All Anagrams in a String, Longest Repeating Character Replacement.

Common mistake: Forgetting to shrink the window correctly, or not resetting frequency counters when the window moves.


3. Fast & Slow Pointers (Cycle Detection)

What it is: Also called the Tortoise and Hare technique. Two pointers move through a linked list or array at different speeds (typically 1x and 2x).

When to use it: Cycle detection, finding the middle of a linked list, finding the start of a cycle, detecting "happy numbers."

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True
    return False

Classic problems: Linked List Cycle I & II, Middle of the Linked List, Happy Number, Find the Duplicate Number.


4. Merge Intervals

What it is: Sort intervals by start time, then walk through and merge any that overlap.

When to use it: Anything involving scheduling, calendars, ranges, or overlapping time windows.

def merge_intervals(intervals):
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged

Classic problems: Merge Intervals, Insert Interval, Non-overlapping Intervals, Meeting Rooms I & II, Employee Free Time.

Common mistake: Forgetting to sort first — this pattern only works cleanly once intervals are ordered by start time.


5. Prefix Sum

What it is: Precompute cumulative sums so that any range-sum query becomes O(1) instead of re-summing every time.

When to use it: "Sum of elements from index i to j," subarray sum equal to k, range queries repeated many times.

nums = [1, 2, 3, 4, 5]
prefix = [0] * (len(nums) + 1)
for i in range(len(nums)):
    prefix[i + 1] = prefix[i] + nums[i]

# Sum from index 1 to 3 (inclusive)
print(prefix[4] - prefix[1])

Classic problems: Subarray Sum Equals K, Range Sum Query — Immutable, Product of Array Except Self, Continuous Subarray Sum.


6. Binary Search & Binary Search on Answer

What it is: Repeatedly halve the search space. The version most candidates miss is "binary search on the answer" — used when the array itself isn't sorted, but the answer space (e.g., possible speeds, capacities, or days) is monotonic.

When to use it: Sorted arrays, finding boundaries (first/last occurrence), rotated sorted arrays, or minimizing/maximizing a value where "can I achieve X?" gets easier or harder monotonically as X changes.

def binary_search_answer(low, high, feasible):
    while low < high:
        mid = (low + high) // 2
        if feasible(mid):
            high = mid
        else:
            low = mid + 1
    return low

Classic problems: Search in Rotated Sorted Array, Find First and Last Position, Koko Eating Bananas, Capacity to Ship Packages Within D Days, Median of Two Sorted Arrays.

Common mistake: Off-by-one errors in the low/high/mid boundaries — always trace through a 2–3 element example before coding.


7. Hash Map / Frequency Counting

What it is: Trade space for time by storing counts, indices, or complements in a hash map to turn O(n²) lookups into O(1) average-case lookups.

When to use it: Anagram checks, "have I seen this before," pair-sum lookups, grouping by a computed key.

Classic problems: Two Sum, Group Anagrams, Longest Consecutive Sequence, Valid Anagram, Subarray Sum Equals K (combined with prefix sums).

Interview tip: If your instinct is "brute force with nested loops," ask yourself: "What am I looking up repeatedly? Can a hash map make that O(1)?" This single question resolves a huge share of array/string problems.


8. In-Place Reversal of a Linked List

What it is: Reverse pointers as you traverse, using three pointers (prev, curr, next) instead of extra space.

def reverse_list(head):
    prev = None
    curr = head
    while curr:
        next_node = curr.next
        curr.next = prev
        prev = curr
        curr = next_node
    return prev

Classic problems: Reverse Linked List, Reverse Linked List II (between positions), Reverse Nodes in k-Group, Swap Nodes in Pairs, Palindrome Linked List.


9. Tree BFS (Level Order Traversal)

What it is: Traverse a tree level by level using a queue.

When to use it: Anything asking for level-wise output, shortest path in an unweighted tree/graph, or "minimum depth."

from collections import deque

def level_order(root):
    if not root:
        return []
    result, queue = [], deque([root])
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node.val)
            if node.left: queue.append(node.left)
            if node.right: queue.append(node.right)
        result.append(level)
    return result

Classic problems: Binary Tree Level Order Traversal, Zigzag Level Order, Minimum Depth of Binary Tree, Binary Tree Right Side View.


10. Tree DFS (Preorder / Inorder / Postorder)

What it is: Recursively (or with an explicit stack) traverse down one branch before backtracking.

When to use it: Path-sum problems, validating BST properties, tree serialization, computing depth/diameter.

def max_depth(root):
    if not root:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))

def has_path_sum(root, target):
    if not root:
        return False
    if not root.left and not root.right:
        return target == root.val
    remaining = target - root.val
    return has_path_sum(root.left, remaining) or has_path_sum(root.right, remaining)

Classic problems: Validate Binary Search Tree, Path Sum I/II, Lowest Common Ancestor, Diameter of Binary Tree, Serialize/Deserialize Binary Tree.

Mental model: DFS problems almost always fall into "pass state down" (parameters) or "pass state up" (return values) — deciding which one you need is 80% of solving the problem.


11. Graph Traversal — BFS, DFS, Topological Sort, Union-Find

What it is: Graphs generalize trees — the same BFS/DFS ideas apply, plus a few graph-specific tools:

  • BFS → shortest path in an unweighted graph, level-order spread (e.g., rotting oranges, multi-source BFS).

  • DFS → connectivity, cycle detection, island-counting on grids.

  • Topological Sort (Kahn's algorithm or DFS-based) → ordering with dependencies (course schedules, build systems).

  • Union-Find (Disjoint Set) → dynamic connectivity, detecting cycles in undirected graphs, Kruskal's MST.

  • Dijkstra's Algorithm → weighted shortest path with non-negative weights.

Classic problems: Number of Islands, Course Schedule I/II, Clone Graph, Rotting Oranges, Word Ladder, Network Delay Time, Redundant Connection.

Interview tip: Know when to use an adjacency list vs. adjacency matrix — sparse graphs (most interview graphs) favor adjacency lists.


12. Backtracking

What it is: Explore all candidate solutions incrementally, and "undo" (backtrack) a choice the moment it's known to be invalid — pruning the search space instead of blindly generating everything.

When to use it: Anything asking for "all possible" combinations, permutations, or valid configurations — subsets, N-Queens, Sudoku.

def subsets(nums):
    result = []
    def backtrack(start, path):
        result.append(path[:])
        for i in range(start, len(nums)):
            path.append(nums[i])
            backtrack(i + 1, path)
            path.pop()
    backtrack(0, [])
    return result

Classic problems: Subsets, Permutations, Combination Sum, Generate Parentheses, N-Queens, Word Search, Sudoku Solver.

Common mistake: Forgetting to "revert state" (pop from the path, unmark visited cells) after the recursive call returns.


13. Dynamic Programming (1D & 2D)

What it is: Break a problem into overlapping subproblems, solve each one once, and store ("memoize") the result to avoid recomputation. DP problems have two ingredients: overlapping subproblems and optimal substructure.

When to use it: Optimization problems (max/min/count ways) where a brute-force recursive solution would repeat the same subproblem many times.

Approach to identify DP:

  1. Can you express the answer for n in terms of smaller n?

  2. Does the brute-force recursive tree have repeated subtrees?

  3. If yes to both — memoize (top-down) or build a table (bottom-up).

def climb_stairs(n):
    if n <= 2:
        return n
    dp = [0] * (n + 1)
    dp[1], dp[2] = 1, 2
    for i in range(3, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[n]

Classic problems: Climbing Stairs, House Robber I/II/III, Coin Change, Longest Common Subsequence, Edit Distance, Longest Increasing Subsequence, 0/1 Knapsack, Unique Paths, Best Time to Buy and Sell Stock (I–IV), Word Break.

Reality check: DP is famously the pattern candidates fear most — and it does appear less frequently than arrays/strings/graphs at most companies, but shows up heavily at Google-style interviews and senior-level rounds. It's worth dedicated practice time even though it's not the most frequent pattern.


14. Heap / Top-K Elements

What it is: A priority queue (min-heap or max-heap) gives you the smallest/largest element in O(log n), letting you avoid a full O(n log n) sort when you only need the top or bottom k elements.

When to use it: "Top K," "Kth largest," running median, merging K sorted lists, task scheduling.

import heapq

def top_k_frequent(nums, k):
    from collections import Counter
    count = Counter(nums)
    return heapq.nlargest(k, count.keys(), key=count.get)

Classic problems: Kth Largest Element in an Array, Top K Frequent Elements, Find Median from Data Stream, Merge K Sorted Lists, Task Scheduler.

Interview tip: Python's heapq is a min-heap by default — push negative values to simulate a max-heap.


15. Monotonic Stack

What it is: A stack that maintains elements in strictly increasing or decreasing order, popping elements as needed. It's the go-to technique for "next greater/smaller element" style problems.

When to use it: Next Greater Element, histogram/rectangle area problems, stock span, daily temperatures.

def daily_temperatures(temps):
    result = [0] * len(temps)
    stack = []  # stores indices
    for i, temp in enumerate(temps):
        while stack and temps[stack[-1]] < temp:
            prev_index = stack.pop()
            result[prev_index] = i - prev_index
        stack.append(i)
    return result

Classic problems: Daily Temperatures, Next Greater Element I/II, Largest Rectangle in Histogram, Trapping Rain Water (stack variant), Stock Span Problem.


How to Actually Practice These Patterns

Knowing the list isn't the same as being interview-ready. Here's a practical approach:

  1. Learn one pattern at a time. Solve 5–8 problems per pattern before moving to the next — enough to see the variations, not so many that you're just grinding.

  2. Time-box recognition, not just solving. Before writing code, spend 60–90 seconds asking: "Which pattern is this?" This is the actual skill interviews test.

  3. Redo problems after a gap. If you solved a problem once, revisit it after a week without looking at your old solution — this is what builds true pattern recall under pressure.

  4. Narrate your thinking out loud, even when practicing alone. Interviewers grade communication as much as correctness — stating your approach before coding, testing with an example, and handling edge cases (empty input, single element, duplicates) all matter.

  5. Track patterns by frequency for your target companies. Array/string-heavy companies (PayPal, Oracle) reward strong Two Pointers/Sliding Window/Hash Map fluency; graph-heavy companies (Uber) reward strong BFS/DFS/Union-Find fluency. Tailor your last two weeks of prep accordingly.

  6. Use a structured sheet like NeetCode 150 or Blind 75 to make sure you've touched every pattern at least once before your interview loop.


Final takeaway: Interviewers aren't testing whether you've memorized 500 problems — they're testing whether you can recognize which of these 15 tools fits the problem in front of you, explain your reasoning, and implement it cleanly under time pressure. Master the pattern, not the problem, and the problems start solving themselves.

Free DSA AI Interview

Start Free DSA AI Interview Practice

Register Free

Frequently Asked Questions

How many DSA patterns should I know for interviews?

Around 15–20 core patterns cover the large majority of questions asked at most companies. Some prep resources extend this into 90 sub-patterns, but those are really variations within the 15–20 core families listed above.

Which DSA pattern is most important for interviews?

Two Pointers, Sliding Window, Hash Map, and Tree/Graph BFS-DFS are the highest-frequency patterns across most companies. Dynamic Programming appears less often overall but is weighted heavily at companies like Google and in senior-level interviews.

Is Dynamic Programming necessary for freshers?

It's worth knowing the basics (1D DP, simple 2D DP like Unique Paths or Edit Distance), but don't over-invest early. Arrays, strings, hash maps, and trees give a better return on time for entry-level interviews.

What's the difference between Sliding Window and Two Pointers?

Two Pointers usually deals with pairs or fixed relationships between indices (often on sorted data). Sliding Window specifically tracks a contiguous range that expands and contracts based on a condition — it's really a specialized form of the two-pointer idea.

How long does it take to master these patterns?

With focused practice (5–8 problems per pattern, revisited after a gap), most candidates get comfortable with all 15 patterns in 8–12 weeks of consistent daily practice.