Advanced

Pattern Recognition Guide

This is your reference card. Every problem in this course maps to one of 8 core patterns. Learn to identify the pattern in the first 2 minutes of reading a problem, and you will solve it faster than someone who has memorized the solution but does not understand the pattern.

The Pattern Decision Tree

When you read a new problem, ask these questions in order:

💡
Quick Decision Framework:
  1. Does the problem involve a sorted array or finding a pair/triplet? → Two Pointers or Binary Search
  2. Does it ask for a contiguous subarray/substring with some property? → Sliding Window
  3. Does it involve matching, nesting, or LIFO order? → Stack
  4. Does it ask for O(1) lookup or grouping by key? → Hash Map / Set
  5. Does it involve a tree or graph traversal? → BFS or DFS
  6. Does it ask for min/max of something with overlapping subproblems? → Dynamic Programming
  7. Does it ask for top k or k-th largest/smallest? → Heap
  8. Does it ask for an optimal schedule or assignment? → Greedy or Heap

Complete Problem-to-Pattern Map

Here is every problem in this course mapped to its primary pattern, with the key insight that unlocks the solution.

Pattern 1: Hash Map / Set

#ProblemKey Insight
1Two SumStore complement in map; check before inserting
10Contains DuplicateSet membership check is O(1)
15Group AnagramsSorted string or char count tuple as hash key
18Subarray Sum Equals KPrefix sum + hash map of frequencies

Pattern 2: Two Pointers

#ProblemKey Insight
3Merge Two Sorted ListsCompare heads, advance the smaller one
5Valid PalindromeCompare from both ends, skip non-alphanumeric
6Linked List CycleFast/slow pointers meet if cycle exists
113SumFix one element, two pointers on sorted remainder
12Container With Most WaterStart widest, shrink from shorter side
43Trapping Rain WaterTrack left_max and right_max from both ends

Pattern 3: Sliding Window

#ProblemKey Insight
13Longest Substring Without RepeatingExpand right, shrink left on duplicate
47Sliding Window MaximumMonotonic deque maintains decreasing order
50Minimum Window SubstringExpand to satisfy, shrink to minimize

Pattern 4: Stack

#ProblemKey Insight
2Valid ParenthesesPush openers, pop and match closers
37Min StackAuxiliary stack tracks min at each level
48Largest Rectangle in HistogramMonotonic increasing stack; pop on shorter bar

Pattern 5: Tree / Graph Traversal (BFS & DFS)

#ProblemKey Insight
8Binary Tree InorderLeft-Root-Right with stack or recursion
21Level Order TraversalBFS with queue, process one level at a time
22Validate BSTDFS with valid range (min, max) passed down
23Number of IslandsDFS flood fill on each unvisited land cell
24Course ScheduleTopological sort detects cycles in DAG
25Word SearchBacktracking DFS with visited marking
26Clone GraphDFS/BFS + hash map from original to clone
27Binary Tree PathsDFS with path string building
28Kth Smallest in BSTInorder traversal gives sorted order; stop at k
29Serialize/Deserialize TreePreorder with null markers for reconstruction
30Lowest Common AncestorRecursive DFS; node is LCA if both subtrees return non-null
46Word LadderBFS on implicit graph of one-letter changes

Pattern 6: Dynamic Programming

#ProblemKey Insight
7Climbing Stairsdp[i] = dp[i-1] + dp[i-2] (Fibonacci variant)
9Maximum SubarrayKadane's: current_sum = max(num, current_sum + num)
31Coin Changedp[amount] = min coins; try each coin denomination
32Word Breakdp[i] = can s[0:i] be segmented; check all splits
33House Robberdp[i] = max(skip, rob + dp[i-2])
34Unique Pathsdp[i][j] = dp[i-1][j] + dp[i][j-1]
35Decode WaysLike climbing stairs but with digit constraints
44Longest Palindromic SubstringExpand around each center (not classic DP table)
45Edit Distance2D DP: insert, delete, replace transitions
49Regular Expression Matching2D DP: handle '.' and '*' transitions carefully

Pattern 7: Binary Search

#ProblemKey Insight
41Median of Two Sorted ArraysBinary search on partition of shorter array

Pattern 8: Heap / Greedy

#ProblemKey Insight
38Top K Frequent ElementsBucket sort by frequency or min heap of size k
39Meeting Rooms IIMin heap of end times; reuse room if available
40Task SchedulerGreedy: most frequent task determines structure
42Merge K Sorted ListsMin heap of k list heads; always pop smallest

Other Patterns

#ProblemPatternKey Insight
4Best Time to Buy/Sell StockTrack MinTrack minimum price seen; max profit = price - min
14Product of Array Except SelfPrefix/SuffixLeft pass for prefixes, right pass for suffixes
16Merge IntervalsSort + ScanSort by start; merge if overlap with previous
17Sort ColorsThree-way PartitionDutch National Flag with three pointers
19Rotate ArrayReverseReverse all, reverse first k, reverse rest
20Spiral MatrixSimulationShrink boundaries after each pass
36LRU CacheDesignHash map + doubly linked list for O(1) operations

How to Identify Patterns Quickly

Here are the trigger words and phrases that point to each pattern:

PatternTrigger Words in Problem Statement
Hash Map"find pair", "two numbers that", "group", "frequency", "count occurrences"
Two Pointers"sorted array", "pair/triplet", "palindrome", "in-place", "cycle"
Sliding Window"contiguous subarray", "substring", "window of size k", "longest/shortest"
Stack"matching brackets", "nested", "next greater", "monotonic", "undo"
BFS/DFS"shortest path", "connected components", "levels", "tree", "graph", "grid"
DP"minimum/maximum", "number of ways", "can you reach", "subsequence", "partition"
Binary Search"sorted", "find position", "minimize maximum", "O(log n)"
Heap"top k", "k-th largest", "merge k", "schedule", "priority"

Pattern Frequency at AI/ML Companies

Based on interview data, here is how frequently each pattern appears:

PatternFrequencyMust-Know Problems
Hash Map / SetVery High (25%)Two Sum, Group Anagrams, Subarray Sum K
Tree / GraphHigh (20%)Number of Islands, Course Schedule, LCA
Dynamic ProgrammingHigh (18%)Coin Change, Word Break, Edit Distance
Two PointersMedium (12%)3Sum, Trapping Rain Water
Sliding WindowMedium (8%)Longest Substring, Minimum Window
DesignMedium (7%)LRU Cache, Min Stack
HeapMedium (6%)Merge K Lists, Top K Frequent
StackLow (4%)Valid Parentheses, Largest Rectangle

Key Takeaways

  • There are only 8 core patterns. Every problem is a variation of one (or occasionally two) patterns.
  • Spend 2 minutes reading the problem and identifying the pattern before writing any code. This saves time in the long run.
  • Hash maps and tree/graph traversal account for nearly half of all interview questions at AI/ML companies.
  • When stuck, try the trigger word analysis: look for keywords in the problem statement that map to patterns.
  • Print this page and use it as a reference card during practice sessions.