Top 50 Python DSA Problems by Pattern (With Solutions)

Interviewers don't test 50 random problems — they test ~10 patterns wearing different costumes. Learn the pattern once, and every problem in its family falls. Here are the 50 highest-yield DSA problems grouped by pattern, each with the one-line approach and the template code to memorize.

New companion post: every one of these 50 problems stated as an interview question with a complete, runnable Python solution — 50 Python DSA Interview Questions & Answers — Solved by Pattern.

Pattern 1 — Two Pointers (5)

# template: converge from both ends
l, r = 0, len(a) - 1
while l < r:
    if condition(a[l], a[r]): return True
    l, r = move(l, r)   # shrink toward the target
  • Two Sum II (sorted) — pointers converge; move the side that's too big/small.
  • Container With Most Water — move the shorter wall; area = min(h) × width.
  • 3Sum — fix one element, two-pointer the rest; skip duplicates.
  • Valid Palindrome — converge, skipping non-alphanumerics.
  • Trapping Rain Water — track left/right max; water = min(maxL, maxR) − height.

Pattern 2 — Sliding Window (5)

# template: expand right, shrink left while invalid
l = 0
for r, ch in enumerate(s):
    window[ch] += 1
    while invalid(window):
        window[s[l]] -= 1; l += 1
    best = max(best, r - l + 1)
  • Longest Substring Without Repeating Characters — window + set; shrink on duplicate.
  • Minimum Window Substring — expand until all targets covered, then shrink.
  • Longest Repeating Character Replacement — window valid while (len − maxfreq) ≤ k.
  • Permutation in String — fixed-size window; compare frequency maps.
  • Max Sum Subarray of Size K — the fixed-window warm-up; running sum.

Pattern 3 — Hash Map (5)

# template: one pass, store what you've seen
seen = {}
for i, x in enumerate(a):
    if target - x in seen: return [seen[target - x], i]
    seen[x] = i
  • Two Sum — complement lookup; the hash map hello-world.
  • Group Anagrams — key = sorted word (or char-count tuple).
  • Top K Frequent Elements — Counter + heap, or bucket sort by frequency.
  • Longest Consecutive Sequence — only start counting at sequence starts (x−1 not in set) → O(n).
  • Subarray Sum Equals K — prefix sums in a map; count of (prefix − k).

Pattern 4 — Stack (5)

  • Valid Parentheses — push opens, match closes; stack empty at end.
  • Min Stack — parallel stack tracking the min at each depth.
  • Daily Temperatures — monotonic decreasing stack; pop while current is warmer.
  • Largest Rectangle in Histogram — monotonic stack of bar indices; the hard one, know it.
  • Evaluate Reverse Polish Notation — push operands, apply operators.

Pattern 5 — Binary Search (5)

# template: half-open interval, no off-by-one
lo, hi = 0, len(a)
while lo < hi:
    mid = (lo + hi) // 2
    if a[mid] < target: lo = mid + 1
    else: hi = mid
return lo
  • Binary Search — the template above; memorize the half-open form.
  • Search in Rotated Sorted Array — one half is always sorted; check which.
  • Search a 2D Matrix — flatten mentally to 1D, or stair-step from top-right.
  • Koko Eating Bananas — binary search on the answer (min feasible speed).

Pattern 6 — Trees: BFS & DFS (5)

  • Maximum Depth of Binary Tree — recursion or level-order BFS.
  • Invert Binary Tree — swap children recursively; the famous one.
  • Diameter of Binary Tree — post-order returns depth, tracks max sum.
  • Lowest Common Ancestor — recurse; return node when found in both subtrees.
  • Binary Tree Level Order Traversal — BFS with level-size loop.

Pattern 7 — Heaps (5)

  • Kth Largest Element — min-heap of size k.
  • Merge K Sorted Lists — heap of list heads; the heap interview staple.
  • Top K Frequent Elements — Counter → heap (or bucket sort).
  • Find Median from Data Stream — max-heap (low half) + min-heap (high half).
  • Task Scheduler — max-heap of frequencies + cooldown math.

Pattern 8 — Graphs (5)

  • Number of Islands — DFS/BFS flood fill; count the starts.
  • Clone Graph — DFS + old→new node map.
  • Course Schedule — cycle detection via topological sort (Kahn's).
  • Pacific Atlantic Water Flow — reverse thinking: flow uphill from both oceans.
  • Word Ladder — BFS on word graph; pattern buckets (*ot, h*t) as edges.

Pattern 9 — Dynamic Programming (5)

# template: state → recurrence → base cases → order
# Climbing Stairs: dp[i] = dp[i-1] + dp[i-2]
a, b = 1, 1
for _ in range(n - 1):
    a, b = b, a + b   # O(1) space — say this out loud
  • Climbing Stairs — Fibonacci in disguise; then optimize to O(1) space.
  • House Robber — dp[i] = max(dp[i−1], dp[i−2] + nums[i]).
  • Coin Change — unbounded knapsack; dp[amount] = min coins.
  • Longest Increasing Subsequence — O(n²) DP, then mention O(n log n) patience.
  • 0/1 Knapsack — the parent of half of DP; subset-sum is its child.

Pattern 10 — Intervals (5)

  • Merge Intervals — sort by start; merge overlaps.
  • Insert Interval — one pass, three phases (before / overlap / after).
  • Non-overlapping Intervals — greedy by end time; count removals.
  • Meeting Rooms II — min-heap of end times, or sweep line.
  • Minimum Number of Arrows — sort by end; shoot at the earliest end.

How to use this list

  • Do one pattern per day: memorize the template, then solve its 5 cold.
  • Always state complexity before coding — interviewers score the analysis, not just the code.
  • When stuck, name the pattern out loud: "This smells like sliding window because…" — partial credit is real.

In this series

  1. Top 50 Python DSA Problems by Pattern (With Solutions) (this post).
  2. Data Science Interview Questions: Statistics, pandas, SQL — the three muscles.
  3. Machine Learning Interview Questions — Distilled From 7 Tutorials — regression to deployment.

Full Python roadmap: Python Learning Roadmap 2026 — all 50 tutorials across 8 tracks.

Comments

Popular posts from this blog

Java Banking Finance Services and Insurance (BFSI) domain interview questions

JSP Servlet Interview Questions For Freshers Series 1

Java program to check even or odd number