Pattern Cheat Sheet & Practice Plan
- 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, declarevar dfs func(...)before a recursive closure, and knowcontainer/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
| Pattern | Recognition signal | Template / key move | Typical cost | Deep dive |
|---|---|---|---|---|
| Hash map / counting | "seen before?", pairs summing to X, group by key, count | m[k]++; look up the complement before inserting | O(n) time, O(n) space | Arrays & Hashing |
| Prefix sums | range sums, "subarray sum = k", negatives allowed | P[i+1] = P[i] + a[i]; count P[j] − k in a map | O(n) | Arrays & Hashing |
| Converging two pointers | sorted input, pair/triplet target, palindrome | move the side that cannot be in any answer | O(n) after sort | Two Pointers & Sliding Window |
| Sliding window | longest/shortest contiguous range with a monotone condition | expand right; while invalid shrink left; record | O(n) | Two Pointers & Sliding Window |
| Fast/slow pointers | list cycle, middle, k-th from end, "duplicate in 1..n" | slow += 1, fast += 2; reset to head for cycle entrance | O(n), O(1) space | Linked Lists |
| Binary search (index) | sorted data, first/last position, O(log n) asked | for lo < hi: pred(mid) → hi = mid, else lo = mid + 1 | O(log n) | Binary Search |
| Binary search on answer | "minimum X such that…", minimize the maximum | search X with a greedy feasibility check | O(n log range) | Binary Search |
| Monotonic stack | next greater/smaller, span, histogram | pop while top breaks the order; popped items get their answer | O(n) | Stacks, Queues & Monotonic Stacks |
| Monotonic deque | max/min of every window | drop stale front; pop smaller backs | O(n) | Stacks, Queues & Monotonic Stacks |
| Heap / top-k | k largest/closest/frequent, repeated min/max | min-heap of size k for the k largest | O(n log k) | Heaps & Priority Queues |
| K-way merge | merge k sorted lists/files/streams | heap of current heads | O(N log k) | Heaps & Priority Queues |
| Two heaps | running median | max-heap low half, min-heap high half | O(log n) per add | Heaps & Priority Queues |
| Intervals | merge, overlap, rooms, scheduling | sort by start to merge; by end to select | O(n log n) | Greedy & Backtracking |
| BFS | minimum steps, levels, nearest, multi-source | queue; mark visited on enqueue | O(V + E) | Graphs |
| DFS / flood fill | components, islands, paths, cycle detection | recursion or stack; visited set; three colours for directed cycles | O(V + E) | Graphs |
| Topological sort | prerequisites, build/deploy order, "is there a cycle" | Kahn: queue in-degree 0 nodes | O(V + E) | Graphs |
| Union-find | dynamic connectivity, merge groups, redundant edge | Find with path compression, union by size | ≈O(1) amortized | Graphs |
| Dijkstra | weighted shortest path, non-negative weights | min-heap over distance; skip stale entries | O((V + E) log V) | Graphs |
| Tree DFS | height, diameter, path sums, LCA, validation | define what the call returns (bottom-up) or passes down (bounds) | O(n) | Trees & BSTs |
| Trie | prefix queries, autocomplete, word search on a board | children array/map plus an end-of-word flag | O(L) per op | Trees & BSTs |
| Backtracking | all subsets/permutations/combinations, constraint puzzles | choose → explore → unchoose; slices.Clone(path) | exponential | Greedy & Backtracking |
| Greedy | locally optimal choice with an exchange argument | sort by the key that makes the choice safe | O(n log n) | Greedy & Backtracking |
| Dynamic programming | count ways, min/max with interacting choices, subsequences | state in words → transition on last decision → base → order | states × transition | Dynamic Programming |
| Bit manipulation | "appears once", subsets of ≤ 20 items, powers of two | x ^ x = 0, x & (x − 1) clears the lowest set bit | O(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
| Step | Time (45-min round) | What you do | What it sounds like |
|---|---|---|---|
| 1. Clarify | 3–5 min | Inputs, 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. Examples | 2–3 min | Walk one normal and one edge example by hand | "For [2, 7, 11, 15] and 9, I expect indexes 0 and 1." |
| 3. Brute force | 2–3 min | State the naive approach and its cost; do not code it unless asked | "Checking every pair is O(n²), too slow for 10⁵." |
| 4. Optimize | 5–10 min | Name 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. Code | 15–20 min | Clean Go with good names and small helpers; narrate invariants | "left is the first index still inside the window." |
| 6. Test | 5 min | Trace the example through your code, then edge cases; fix calmly | "Empty input returns early… single element… all duplicates…" |
| 7. Analyse and extend | 2–3 min | Time 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, thendfs = func(…). - Loop variables are per-iteration since Go 1.22, so closures and goroutines capturing
ibehave as expected — mention it if you capture loop variables. - Integers:
intis 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 withslices.BinarySearch. - Modern helpers: built-in
min,max,clear(Go 1.21);slices.Sort,slices.SortFuncwithcmp.Compare,slices.Reverse,slices.Clone,maps.Keys. - Composite keys:
map[[2]int]boolfor grid cells, structs for memo states — notfmt.Sprintf. - 2D slices: allocate each row (
grid[i] = make([]int, cols)); a singlemake([][]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 strategy | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Pattern-by-pattern lists (NeetCode 150, Blind 75) | Builds recognition systematically; covers essentials | Knowing the topic in advance inflates confidence | First pass (weeks 1–10) |
| Mixed / random problems | Trains recognition without hints | Frustrating before the patterns are familiar | After the first pass; final weeks |
| Company-tagged lists | Matches a target company's style | Noisy, often outdated, sometimes paywalled | 2–3 weeks before a specific interview |
| Timed contests | Speed under pressure | Rewards tricks over clear communication | If you freeze when timed |
| Mock interviews with a person | Trains communication — what is actually graded | Needs a partner and scheduling | Weekly 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.
| Week | Focus | Problems | Read |
|---|---|---|---|
| 1 | Complexity, arrays & hashing | Two Sum (1), Contains Duplicate (217), Valid Anagram (242), Group Anagrams (49), Top K Frequent Elements (347) | Complexity, Arrays & Hashing |
| 2 | Prefix sums, two pointers | Product of Array Except Self (238), Subarray Sum Equals K (560), Valid Palindrome (125), Two Sum II (167), 3Sum (15) | Two Pointers & Sliding Window |
| 3 | Sliding window | Best 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 |
| 4 | Stacks, monotonic stacks | Valid Parentheses (20), Min Stack (155), Evaluate Reverse Polish Notation (150), Daily Temperatures (739), Largest Rectangle in Histogram (84) | Stacks & Queues |
| 5 | Binary search | Binary 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 |
| 6 | Linked lists | Reverse Linked List (206), Merge Two Sorted Lists (21), Linked List Cycle (141), Reorder List (143), LRU Cache (146) | Linked Lists |
| 7 | Trees | Invert Binary Tree (226), Maximum Depth of Binary Tree (104), Level Order Traversal (102), Validate BST (98), Lowest Common Ancestor (236) | Trees & BSTs |
| 8 | Tries, heaps | Implement 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 |
| 9 | Graphs I | Number of Islands (200), Clone Graph (133), Rotting Oranges (994), Course Schedule (207), Course Schedule II (210) | Graphs |
| 10 | Graphs II, intervals | Redundant Connection (684), Network Delay Time (743), Merge Intervals (56), Non-overlapping Intervals (435), Meeting Rooms II (253) | Graphs, Greedy |
| 11 | Backtracking, 1D DP | Subsets (78), Combination Sum (39), Climbing Stairs (70), House Robber (198), Coin Change (322) | Greedy & Backtracking, DP |
| 12 | 2D DP, mocks | Longest Increasing Subsequence (300), Longest Common Subsequence (1143), Edit Distance (72), Word Break (139), plus two timed mocks drawn from weeks 1–11 | DP, 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.SortFuncorcontainer/heapis 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.
Exercise
Run and score a full mock interview:
- Pick two random problems from weeks 1–6 of the plan (not ones you solved in the last week).
- 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.
- Afterwards, score yourself with the Mock Interview Checklist & Scoring on clarification, approach, code quality, testing and communication, and write the three most important improvements.
- 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)
Related
- Complexity Analysis — constraints to complexity.
- Data Structures Inside Real Systems — where interview patterns meet system design.
- 6-Month Roadmap (Interview-Focused) — fitting this plan into the full preparation.
- Books, Courses & Practice Resources — practice platforms and books.
- Question Bank — more questions to rehearse.
- Mock Interview Checklist & Scoring — how to grade your mocks.
- Common Pitfalls — the Go mistakes that also appear in interviews.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).