Skip to main content

Pattern Cheat Sheet & Practice Plan

Learning objectives
  • Map an unfamiliar problem to a pattern within the first few minutes using recognition signals and input constraints
  • Follow a 12-week, ≈5-problems-per-week plan that covers every pattern in this section and fits beside system design preparation
  • Run a coding interview the way it is graded: clarify, examples, brute force, optimize, code, test, analyse
  • Avoid the Go-specific mistakes interviewers notice: slice aliasing, map iteration order, bytes vs runes, recursive closures, integer edge cases

TL;DR​

  • Constraints pick the complexity; the complexity narrows the pattern. n ≤ 20 → exponential search; n ≤ 10⁵ → O(n log n) or better.
  • Twenty-odd patterns cover the vast majority of interview problems. Learn their recognition signals, not individual solutions.
  • Interviews grade the process: clarifying questions, a stated brute force, a justified optimization, clean code, self-testing, and correct complexity. A silent perfect solution scores lower than a narrated good one.
  • Practice in a loop: solve (25–40 min cap) → study the solution → re-implement next day → re-solve after a week and a month.
  • Go tips: clone slices you store (slices.Clone), sort map keys for deterministic output, len(s) counts bytes, declare var dfs func(...) before a recursive closure, and know container/heap, slices, maps, min/max.
  • For architects, coding rounds are usually medium difficulty; communication, correctness and production instincts (overflow, money as integers, input validation) carry as much weight as cleverness.

When to reach for it​

  • You face a new problem and do not know where to start — scan the cheat sheet's "recognition signal" column.
  • Planning your week: the 12-week table tells you which page to study and which problems to solve.
  • The final days before an interview: re-read the TL;DR blocks of each algorithms page, the cheat sheet and the Go tips, then do two timed mocks.

Core concepts​

Pattern cheat sheet​

PatternRecognition signalTemplate / key moveTypical costDeep dive
Hash map / counting"seen before?", pairs summing to X, group by key, countm[k]++; look up the complement before insertingO(n) time, O(n) spaceArrays & Hashing
Prefix sumsrange sums, "subarray sum = k", negatives allowedP[i+1] = P[i] + a[i]; count P[j] − k in a mapO(n)Arrays & Hashing
Converging two pointerssorted input, pair/triplet target, palindromemove the side that cannot be in any answerO(n) after sortTwo Pointers & Sliding Window
Sliding windowlongest/shortest contiguous range with a monotone conditionexpand right; while invalid shrink left; recordO(n)Two Pointers & Sliding Window
Fast/slow pointerslist cycle, middle, k-th from end, "duplicate in 1..n"slow += 1, fast += 2; reset to head for cycle entranceO(n), O(1) spaceLinked Lists
Binary search (index)sorted data, first/last position, O(log n) askedfor lo < hi: pred(mid) → hi = mid, else lo = mid + 1O(log n)Binary Search
Binary search on answer"minimum X such that…", minimize the maximumsearch X with a greedy feasibility checkO(n log range)Binary Search
Monotonic stacknext greater/smaller, span, histogrampop while top breaks the order; popped items get their answerO(n)Stacks, Queues & Monotonic Stacks
Monotonic dequemax/min of every windowdrop stale front; pop smaller backsO(n)Stacks, Queues & Monotonic Stacks
Heap / top-kk largest/closest/frequent, repeated min/maxmin-heap of size k for the k largestO(n log k)Heaps & Priority Queues
K-way mergemerge k sorted lists/files/streamsheap of current headsO(N log k)Heaps & Priority Queues
Two heapsrunning medianmax-heap low half, min-heap high halfO(log n) per addHeaps & Priority Queues
Intervalsmerge, overlap, rooms, schedulingsort by start to merge; by end to selectO(n log n)Greedy & Backtracking
BFSminimum steps, levels, nearest, multi-sourcequeue; mark visited on enqueueO(V + E)Graphs
DFS / flood fillcomponents, islands, paths, cycle detectionrecursion or stack; visited set; three colours for directed cyclesO(V + E)Graphs
Topological sortprerequisites, build/deploy order, "is there a cycle"Kahn: queue in-degree 0 nodesO(V + E)Graphs
Union-finddynamic connectivity, merge groups, redundant edgeFind with path compression, union by size≈O(1) amortizedGraphs
Dijkstraweighted shortest path, non-negative weightsmin-heap over distance; skip stale entriesO((V + E) log V)Graphs
Tree DFSheight, diameter, path sums, LCA, validationdefine what the call returns (bottom-up) or passes down (bounds)O(n)Trees & BSTs
Trieprefix queries, autocomplete, word search on a boardchildren array/map plus an end-of-word flagO(L) per opTrees & BSTs
Backtrackingall subsets/permutations/combinations, constraint puzzleschoose → explore → unchoose; slices.Clone(path)exponentialGreedy & Backtracking
Greedylocally optimal choice with an exchange argumentsort by the key that makes the choice safeO(n log n)Greedy & Backtracking
Dynamic programmingcount ways, min/max with interacting choices, subsequencesstate in words → transition on last decision → base → orderstates × transitionDynamic Programming
Bit manipulation"appears once", subsets of ≤ 20 items, powers of twox ^ x = 0, x & (x − 1) clears the lowest set bitO(n)—

A first-five-minutes decision path​

It is a starting point, not an oracle — many problems combine two patterns (sort + two pointers, BFS + heap, hashing + sliding window). Use the constraints table on Complexity Analysis to sanity-check the choice.

How to talk through a coding interview​

StepTime (45-min round)What you doWhat it sounds like
1. Clarify3–5 minInputs, sizes, value ranges, duplicates, empty input, output format"Can amounts be negative? Is the list sorted? If no answer exists, return an error or −1?"
2. Examples2–3 minWalk one normal and one edge example by hand"For [2, 7, 11, 15] and 9, I expect indexes 0 and 1."
3. Brute force2–3 minState the naive approach and its cost; do not code it unless asked"Checking every pair is O(n²), too slow for 10⁵."
4. Optimize5–10 minName the repeated work, pick a pattern, confirm with the interviewer before coding"The inner loop searches for a complement; a map makes that O(1)."
5. Code15–20 minClean Go with good names and small helpers; narrate invariants"left is the first index still inside the window."
6. Test5 minTrace the example through your code, then edge cases; fix calmly"Empty input returns early… single element… all duplicates…"
7. Analyse and extend2–3 minTime and space; answer follow-ups on scale"O(n) time, O(n) space. If it does not fit in memory, I'd partition by hash."

When stuck: shrink the problem (n = 3, sorted version), write the brute force and look for repeated work, ask "which data structure answers my slow query fast?", work backwards from the target complexity, or ask for a hint — taking a hint and running with it is a positive signal, not a failure.

Go-specific interview tips​

Slice aliasing. append writes into spare capacity of the backing array, so two appends to the same base can clobber each other — and results stored during backtracking change later unless copied.

func aliasingDemo() {
base := make([]int, 3, 10) // len 3, spare capacity 7
a := append(base, 1) // writes into base's backing array
b := append(base, 2) // overwrites the same slot
fmt.Println(a[3], b[3]) // 2 2

c := append(base[:3:3], 1) // full slice expression: cap == len forces a copy
d := append(base[:3:3], 2)
fmt.Println(c[3], d[3]) // 1 2
}

Map iteration order is random. Sort keys when output order matters: slices.Sorted(maps.Keys(m)) (Go 1.23+). Never let a test depend on map order.

Strings are bytes; range yields runes.

func stringsDemo() {
s := "Đà Nẵng"
fmt.Println(len(s)) // 11: bytes, not characters
fmt.Println(utf8.RuneCountInString(s)) // 7 runes
fmt.Println(s[0]) // 196: the first byte of "Đ", not a character
for i, r := range s { // i is a byte offset, r a rune
if r == 'N' {
fmt.Println("N at byte", i) // 5
}
}
runes := []rune(s) // O(n) copy; index runes safely
fmt.Println(string(runes[0]))

var sb strings.Builder // O(n) total; s += x in a loop is O(n²)
for i := range 3 {
sb.WriteString(strconv.Itoa(i)) // string(i) would produce a rune, not "0"
}
fmt.Println(sb.String()) // 012
}

Other gotchas worth a sentence each:

  • Recursive closures need a declaration first: var dfs func(int) int, then dfs = func(…).
  • Loop variables are per-iteration since Go 1.22, so closures and goroutines capturing i behave as expected — mention it if you capture loop variables.
  • Integers: int is 64-bit on 64-bit platforms; overflow wraps silently; / truncates toward zero and % takes the dividend's sign, so -7 % 3 == -1 (use ((a % m) + m) % m).
  • Missing data structures: no built-in set, deque, heap or ordered map — use map[K]struct{}, slices or a ring buffer, container/heap, and sorted slices with slices.BinarySearch.
  • Modern helpers: built-in min, max, clear (Go 1.21); slices.Sort, slices.SortFunc with cmp.Compare, slices.Reverse, slices.Clone, maps.Keys.
  • Composite keys: map[[2]int]bool for grid cells, structs for memo states — not fmt.Sprintf.
  • 2D slices: allocate each row (grid[i] = make([]int, cols)); a single make([][]int, rows) gives nil rows.

Some companies run online assessments that read from stdin (HackerRank/Codility style). Have a fast I/O template ready:

func main() {
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()

var n int
fmt.Fscan(in, &n)
nums := make([]int, n)
for i := range nums {
fmt.Fscan(in, &nums[i])
}
total := 0
for _, v := range nums {
total += v
}
fmt.Fprintln(out, total)
}

Trade-offs​

Practice strategyStrengthsWeaknessesChoose when
Pattern-by-pattern lists (NeetCode 150, Blind 75)Builds recognition systematically; covers essentialsKnowing the topic in advance inflates confidenceFirst pass (weeks 1–10)
Mixed / random problemsTrains recognition without hintsFrustrating before the patterns are familiarAfter the first pass; final weeks
Company-tagged listsMatches a target company's styleNoisy, often outdated, sometimes paywalled2–3 weeks before a specific interview
Timed contestsSpeed under pressureRewards tricks over clear communicationIf you freeze when timed
Mock interviews with a personTrains communication — what is actually gradedNeeds a partner and schedulingWeekly from week 6

In practice​

The 12-week plan​

About five new problems per week plus two or three re-solves, ≈5–7 hours weekly — designed to run beside system design study in the 6-Month Roadmap (Interview-Focused). Read the linked page first, then solve; numbers are LeetCode IDs.

WeekFocusProblemsRead
1Complexity, arrays & hashingTwo Sum (1), Contains Duplicate (217), Valid Anagram (242), Group Anagrams (49), Top K Frequent Elements (347)Complexity, Arrays & Hashing
2Prefix sums, two pointersProduct of Array Except Self (238), Subarray Sum Equals K (560), Valid Palindrome (125), Two Sum II (167), 3Sum (15)Two Pointers & Sliding Window
3Sliding windowBest Time to Buy and Sell Stock (121), Longest Substring Without Repeating Characters (3), Longest Repeating Character Replacement (424), Permutation in String (567), Minimum Window Substring (76)Two Pointers & Sliding Window
4Stacks, monotonic stacksValid Parentheses (20), Min Stack (155), Evaluate Reverse Polish Notation (150), Daily Temperatures (739), Largest Rectangle in Histogram (84)Stacks & Queues
5Binary searchBinary Search (704), Search a 2D Matrix (74), Koko Eating Bananas (875), Search in Rotated Sorted Array (33), Time Based Key-Value Store (981)Binary Search
6Linked listsReverse Linked List (206), Merge Two Sorted Lists (21), Linked List Cycle (141), Reorder List (143), LRU Cache (146)Linked Lists
7TreesInvert Binary Tree (226), Maximum Depth of Binary Tree (104), Level Order Traversal (102), Validate BST (98), Lowest Common Ancestor (236)Trees & BSTs
8Tries, heapsImplement Trie (208), Kth Largest Element in an Array (215), K Closest Points to Origin (973), Merge k Sorted Lists (23), Find Median from Data Stream (295)Heaps
9Graphs INumber of Islands (200), Clone Graph (133), Rotting Oranges (994), Course Schedule (207), Course Schedule II (210)Graphs
10Graphs II, intervalsRedundant Connection (684), Network Delay Time (743), Merge Intervals (56), Non-overlapping Intervals (435), Meeting Rooms II (253)Graphs, Greedy
11Backtracking, 1D DPSubsets (78), Combination Sum (39), Climbing Stairs (70), House Robber (198), Coin Change (322)Greedy & Backtracking, DP
122D DP, mocksLongest Increasing Subsequence (300), Longest Common Subsequence (1143), Edit Distance (72), Word Break (139), plus two timed mocks drawn from weeks 1–11DP, Mock Interview Checklist

Weekly rhythm that works: read the page early in the week; solve one problem per session with a hard cap (25 minutes to an approach, 40 to working code) before reading a solution; if you read a solution, re-implement it from a blank file the next day; re-solve two older problems at the 7- and 30-day marks; one timed mock at the weekend from week 6 on. Keep a log of why you missed a problem (wrong pattern, bug, edge case) — that log is your personal cheat sheet.

Walkthrough 1 — Top K Frequent Words (LeetCode 692)​

Clarify. Return the k most frequent words, ordered by frequency descending, ties broken alphabetically. k is at most the number of distinct words. Words are lowercase.

Brute force. Count with a map, sort the distinct words by (count desc, word asc), take k. O(n + u log u) for u distinct words — often good enough, and worth saying.

func topKFrequentSort(words []string, k int) []string {
counts := make(map[string]int)
for _, w := range words {
counts[w]++
}
uniq := slices.Collect(maps.Keys(counts))
slices.SortFunc(uniq, func(a, b string) int {
if c := cmp.Compare(counts[b], counts[a]); c != 0 {
return c // higher count first
}
return cmp.Compare(a, b) // then alphabetical
})
return uniq[:min(k, len(uniq))]
}

Optimize. The follow-up asks for O(n log k): keep a heap of size k whose root is the worst of the current top k (lowest count; for equal counts, the alphabetically larger word), evict when it exceeds k, and pop into the result from the back.

type wordFreq struct {
word string
count int
}

// worse reports whether a ranks below b.
func worse(a, b wordFreq) bool {
if a.count != b.count {
return a.count < b.count
}
return a.word > b.word
}

type freqHeap []wordFreq // root = worst of the current top k

func (h freqHeap) Len() int { return len(h) }
func (h freqHeap) Less(i, j int) bool { return worse(h[i], h[j]) }
func (h freqHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *freqHeap) Push(x any) { *h = append(*h, x.(wordFreq)) }
func (h *freqHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}

func topKFrequentWords(words []string, k int) []string {
counts := make(map[string]int)
for _, w := range words {
counts[w]++
}
h := make(freqHeap, 0, k+1)
for w, c := range counts {
heap.Push(&h, wordFreq{word: w, count: c})
if h.Len() > k {
heap.Pop(&h) // evict the worst
}
}
out := make([]string, h.Len())
for i := len(out) - 1; i >= 0; i-- { // worst comes out first: fill from the back
out[i] = heap.Pop(&h).(wordFreq).word
}
return out
}

Test. ["i","love","leetcode","i","love","coding"], k = 2 → ["i","love"] (both count 2; "i" < "love"). Edge cases: k equals the distinct count; all words identical; ties at the k-th boundary. Analyse. O(n + u log k) time, O(u) space. Scale follow-up: for a stream of search queries, replace the exact map with a count-min sketch plus the same heap (Data Structures Inside Real Systems).

Walkthrough 2 — A bank-style custom question: money-mule detection​

Banks often ask custom problems framed in their domain. Example: "Given transfers (from, to, amount, time), flag every receiving account that, within any 10-minute window, receives at least 3 transfers from distinct senders totalling at least 50,000,000 VND."

Clarify. Is the window inclusive of exactly 10 minutes? (Assume yes.) Can the same sender count twice? (Distinct senders, but every transfer counts toward the total.) Are replayed duplicates possible? (Assume upstream deduplication by transfer ID.) Output order? (Sorted account IDs.) Amounts are integers in the currency's smallest unit — VND has no minor unit.

Approach. Group by receiver (hash map), sort each group by time, then a sliding window per receiver tracking the running total and a sender → count map, so "distinct senders" is len(map). Shrink while the window spans more than 10 minutes.

type Transfer struct {
From, To string
Amount int64 // smallest currency unit
At time.Time
}

// flagMules returns receivers that, within any window of length w, received
// transfers from at least minSenders distinct senders totalling at least minTotal.
func flagMules(ts []Transfer, w time.Duration, minSenders int, minTotal int64) []string {
byTo := make(map[string][]Transfer)
for _, t := range ts {
byTo[t.To] = append(byTo[t.To], t)
}
var flagged []string
for to, in := range byTo {
slices.SortFunc(in, func(a, b Transfer) int { return a.At.Compare(b.At) })
senders := make(map[string]int) // sender -> transfers inside the window
var total int64
left := 0
for _, t := range in {
senders[t.From]++
total += t.Amount
for t.At.Sub(in[left].At) > w { // shrink until the window spans at most w
old := in[left]
total -= old.Amount
senders[old.From]--
if senders[old.From] == 0 {
delete(senders, old.From)
}
left++
}
if len(senders) >= minSenders && total >= minTotal {
flagged = append(flagged, to)
break
}
}
}
slices.Sort(flagged) // deterministic output despite map iteration
return flagged
}

Test. Three senders at 10:00, 10:04 and 10:09 totalling 60M → flagged; the same at 10:00, 10:04 and 10:11 → not flagged; one sender sending three times → not flagged; exactly 10 minutes apart → flagged (inclusive). Analyse. O(n log n) for the sorts, O(n) space. Architect follow-up: in production this is a streaming rule keyed by receiver with windowed state in a stream processor or Redis, and it raises alerts for review rather than blocking outright (Real-time Fraud Detection Pipeline).

Practice list​

A mixed review set, deliberately not in the 12-week plan — use it for random practice once the patterns are familiar.

  • Easy: Majority Element (169), Missing Number (268), Merge Sorted Array (88), Single Number (136)
  • Medium: Rotate Image (48), Spiral Matrix (54), Set Matrix Zeroes (73), Gas Station (134), Decode Ways (91), Word Search (79), Partition Labels (763)
  • Hard: Trapping Rain Water (42), Word Ladder (127), Serialize and Deserialize Binary Tree (297)

Common pitfalls​

  • Coding before clarifying — then solving a different problem. Symptom: "Oh, the input can be empty?" at minute 35.
  • Silent coding. The interviewer cannot give credit for reasoning they cannot hear, or steer you away from a dead end.
  • Skipping the brute force and getting stuck with nothing on the board.
  • Not testing your own code — leaving the interviewer to find the off-by-one.
  • Memorizing solutions instead of signals. A small twist (negative numbers, a stream instead of an array) breaks a memorized answer.
  • Grinding without review. Hundreds of problems solved once each retain less than sixty problems re-solved at spaced intervals.
  • Fighting Go instead of using it: reimplementing sort or a heap from scratch when slices.SortFunc or container/heap is expected, or the opposite — not knowing how either works when asked.
  • Ignoring production instincts in a bank interview: floats for money, unchecked overflow, panicking on empty input.

Interview angle​

  • At banks and e-commerce companies, architect-track coding rounds are typically one or two medium problems, sometimes domain-flavoured (transactions, orders, inventory). The bar is correct, clean, tested code with clear reasoning, not competition tricks.
  • Interviewers watch for: clarifying questions, naming the brute force, justifying the optimization, readable Go (good names, small helpers, early returns), testing unprompted, and accurate complexity.
  • Expect a scale follow-up that bridges into system design: "What if this is a stream?", "What if it does not fit in memory?", "How would this run across 20 instances?" — answer with partitioning, external sorting, sketches, and shared state; that is where an architect stands out.
  • Red flags: no questions, no tests, defensive reactions to hints, claiming complexity incorrectly, or code that only works on the example.
  • More question practice lives in the Question Bank; score your mocks with the Mock Interview Checklist & Scoring.

Self-check​

1. Which signals distinguish a sliding-window problem from a prefix-sum-plus-map problem?

Both involve contiguous subarrays. A sliding window needs a monotone validity condition — for example non-negative values or a distinct-count limit — so shrinking from the left always moves toward validity; it typically asks for the longest or shortest window. Prefix sum plus map handles exact-sum counting and negative values, where monotonicity fails.

2. List the seven steps of a coding interview and what you produce at each.

Clarify (assumptions and edge cases agreed), examples (a worked normal and edge case), brute force (an approach plus its complexity), optimize (the chosen pattern and why), code (clean Go with narrated invariants), test (a trace through the code plus edge cases), analyse (time/space and scale follow-ups).

3. Why can two appends to the same slice overwrite each other, and how do you prevent it?

If the slice has spare capacity, append writes into the shared backing array without allocating, so both results see the last write in that slot. Prevent it with a full slice expression s[:len(s):len(s)] (forces a copy on append), with slices.Clone, or by never keeping two derived slices from the same base.

4. What do len, indexing and range return for a Go string containing Vietnamese text?

len returns the number of bytes (UTF-8 encoded, so characters like "Đ" take two bytes and "ẵ" three). Indexing s[i] returns a single byte. range decodes UTF-8 and yields the byte offset and the rune. Use utf8.RuneCountInString for character counts and []rune(s) to index characters.

5. Map the constraint "n ≤ 18, return the minimum cost to visit every node" to a pattern.

n ≤ 18 allows O(2ⁿ · n²) ≈ 85M operations, which suggests bitmask DP: the state is (set of visited nodes, current node), with transitions to unvisited nodes — the travelling-salesman DP. Backtracking without memoization would be O(n!), far too slow.

6. Scenario: your solution is correct but O(n log n); the interviewer asks for O(n). How do you proceed?

Identify where the log factor comes from (usually a sort or a heap). Ask whether the ordering is really needed or whether a hash map, counting or bucket approach can replace it (e.g. bucket sort by frequency for top-k), and whether input properties (bounded values, small alphabet) allow counting. Explain the trade-off out loud — often O(n) costs more memory — before rewriting.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Run and score a full mock interview:

  1. Pick two random problems from weeks 1–6 of the plan (not ones you solved in the last week).
  2. Set a 45-minute timer, record your audio (or work with a partner), and follow the seven steps out loud. Write code in a plain editor without autocomplete.
  3. Afterwards, score yourself with the Mock Interview Checklist & Scoring on clarification, approach, code quality, testing and communication, and write the three most important improvements.
  4. Repeat every week from week 6, and track the scores in your log.

Done when you have four scored mocks, the scores trend upward, and your "why I missed it" log has turned into a personal one-page list of recurring mistakes.

Further reading​

  • Gayle Laakmann McDowell, Cracking the Coding Interview (6th ed.) — interview process and the classic problem set
  • Aziz, Lee, Prakash, Elements of Programming Interviews — deeper problems by topic
  • Tech Interview Handbook (Yangshun Tay, techinterviewhandbook.org) — study plans, cheat sheets, and the origin of the Blind 75 list
  • NeetCode roadmap and NeetCode 150 (neetcode.io) — pattern-ordered problem list with video explanations
  • Rob Pike, "Strings, bytes, runes and characters in Go" — The Go Blog
  • "Fixing For Loops in Go 1.22" — The Go Blog (per-iteration loop variables)
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).