🏠 Hub 💻 DSA Master Notes Tier 1, 2, 3 • 8+ YoE Guide
Page 1 / 14

Multi-Tier Strategy & 6-Week Master Roadmap

Targeted preparation framework for Senior & Staff (8+ YoE) algorithmic interviews
1

Senior Interview Realities: Tier 1 vs Tier 2 vs Tier 3

Know Your Audience
🚀
Tier 1: Big Tech
Meta • Google • Uber • Stripe
  • Format: 2 Medium/Hard in 45 mins
  • Bar: Zero bugs + Big-O trade-offs
  • Focus: Speed, edge cases, optimal proofs
  • Key: Monotonic Stack, Graphs, Hard DP
🏗️
Tier 2: Product Giants
Salesforce • Atlassian • Adobe • Intuit
  • Format: 1 Hard or Custom DS design
  • Bar: Clean modular OOP & abstractions
  • Focus: Concurrency safety & clarity
  • Key: LRU/LFU Cache, Rate Limiters, Feeds
⚡
Tier 3: Rapid Scale-ups
Walmart • Scale-ups • Fintechs
  • Format: 100% Online Assessment pass
  • Bar: Pass hidden boundary test cases
  • Focus: Pragmatic code & core libs
  • Key: Arrays, Strings, HashMaps, Trees
2

The 45-Minute Live Interview Time Budget

⏱️
0 - 5 min
1. Clarify & Edge Cases
Clarify bounds ($N$, data types, duplicates, negatives). Write 2 custom edge cases before coding!
🧠
5 - 15 min
2. Formulate & Trade-offs
State brute-force ($O(N^2)$), then optimize to $O(N \log N)$ or $O(N)$. Confirm Big-O alignment first!
💻
15 - 35 min
3. Clean Modular Code
Write production-grade code with descriptive names, helper functions, and early guard clauses.
🔍
35 - 45 min
4. Dry-Run & Scale
Step through code line-by-line with sample input. Answer follow-ups on memory & concurrency.
3

Constraint-to-Pattern Meta Decision Matrix

Input Size ($N$) Target Time Complexity Primary DSA Patterns to Match
$N \le 12$ $O(N!)$ or $O(N^2 \cdot 2^N)$ Backtracking Permutations, Traveling Salesperson, TSP DP
$N \le 20 \dots 25$ $O(2^N)$ Subsets, Combination Sum, Bitmask DP
$N \le 100 \dots 500$ $O(N^3)$ or $O(N^4)$ Floyd-Warshall, Matrix Chain Multiplication, 3D Dynamic Programming
$N \le 2\,000 \dots 5\,000$ $O(N^2)$ 2D Matrix DP, Nested Two Pointers, All-Pairs Check
$N \le 10^5 \dots 10^6$ $O(N \log N)$ or $O(N)$ Sorting, Binary Search on Answer, Heaps, Sliding Window, Monotonic Stack, DSU
$N \ge 10^9$ $O(\log N)$ or $O(1)$ Pure Binary Search, Matrix Exponentiation, Math / Bitwise Hacks
4

The 6-Week Roadmap (sketched)

START offer! W1 Arrays & Hash Two Pointers Sliding Window W2 Search & Stacks Binary Search Monotonic Stack W3 Trees & Heaps BST · Trie Top-K · Two Heaps W4 Graphs BFS/DFS · Topo DSU · Dijkstra W5 DP & Backtrack Knapsack · LCS Subsets · Queens W6 LRU · Threads 2 mocks/wk Mocks ~3 problems/day · 2 new + 1 revisit · ≈ 120 problems total
Fig 1.1 — learn patterns, not problems: each week unlocks a family of ~20 problems

🔁 Spaced repetition

  • Re-solve on day 1 → 3 → 7 → 21
  • If you can't code it in 20 min, it goes back in the queue

📓 Pattern journal

  • 1 line per problem: "trigger words → pattern → trick"
  • e.g. "longest substring w/o repeat → window + lastSeen map"

⏲️ Timebox rule

  • Stuck 25 min? Read the hint, not the solution
  • Stuck 40 min? Study it, then re-code from memory tomorrow
🎯 Key Takeaway

"Senior interviews evaluate your decision framework & trade-offs, not rote syntax!"

"Never code in silence — interviewers want to see how you formulate hypotheses, think out loud, and pivot when stuck." 😊

Master Complexity Cheat Sheet & Sorting

1

Core Data Structure Time & Space Complexity Matrix

Data Structure Access / Search Insertion Deletion Space
Dynamic Array / Vector $O(1)$ / $O(N)$ $O(1)$ Amortized $O(N)$ $O(N)$
Doubly Linked List $O(N)$ / $O(N)$ $O(1)$ (with node ptr) $O(1)$ (with node ptr) $O(N)$
Hash Map / Hash Set $O(1)$ Avg, $O(N)$ Worst $O(1)$ Avg $O(1)$ Avg $O(N)$
Binary Search Tree (Balanced) $O(\log N)$ $O(\log N)$ $O(\log N)$ $O(N)$
Binary Heap (Priority Queue) $O(1)$ Peek, $O(N)$ Search $O(\log N)$ Push $O(\log N)$ Pop $O(N)$
Trie (Prefix Tree) $O(L)$ (where $L$ = word len) $O(L)$ $O(L)$ $O(N \cdot L \cdot \Sigma)$
Disjoint Set (Union-Find) $O(\alpha(N)) \approx O(1)$ $O(\alpha(N)) \approx O(1)$ — $O(N)$
2

Sorting Algorithms Comparison: In-Place vs Stable

⚡ QuickSort ($O(N \log N)$ avg, $O(N^2)$ worst)
In-Place ($O(\log N)$ stack), Unstable. Uses partition (Hoare's vs Lomuto). Standard for primitive types in standard libraries.
🥞 MergeSort ($O(N \log N)$ always)
Stable, requires $O(N)$ auxiliary memory. Preferred for sorting Linked Lists ($O(1)$ space) and external storage streams.
🏔️ HeapSort ($O(N \log N)$ always)
In-Place ($O(1)$ aux memory), Unstable. Builds heap in $O(N)$ via `heapify`, extracts min/max in $O(\log N)$.
🔢 Counting / Radix Sort ($O(N + K)$)
Non-comparative, Stable. Ideal when integers lie in known range $K \ll N$. Used for sorting fixed-length strings/integers.
3

How Fast Do the Curves Blow Up? (sketch)

✅ fits 1-sec budget at n = 10⁶ 💀 TLE zone — only for tiny n ops n → O(1) O(log n) O(n) O(n log n) O(n²) O(2ⁿ)
Fig 2.1 — rule of thumb: ~10⁸ simple ops ≈ 1 second (C#/Java/C++) · Python ≈ 10⁷

📐 Master theorem (cheat)

  • $T(n) = T(n/2) + O(1)$ → $O(\log n)$ (binary search)
  • $T(n) = 2T(n/2) + O(1)$ → $O(n)$ (tree DFS)
  • $T(n) = 2T(n/2) + O(n)$ → $O(n \log n)$ (merge sort)

🧮 Space gotchas

  • Recursion depth counts! DFS on skewed tree = $O(n)$ stack
  • String concat in a loop = $O(n^2)$ → use StringBuilder
  • Sorting in C# (introsort) uses $O(\log n)$ stack

⚖️ Amortized ≠ average

  • List.Add doubles capacity → copy cost spread out = $O(1)$ amortized
  • Hash map is $O(1)$ average; adversarial keys → $O(n)$
⚡ Senior Architectural Nuance: CPU Cache Locality
Arrays beat Linked Lists in real systems by a factor of 5-10x because sequential array elements reside in contiguous CPU L1/L2 cache lines, minimizing cache misses. Mentioning this in Tier 1/2 interviews demonstrates senior systems depth!

Arrays, Strings & Matrix Manipulations

1

Prefix Sum & Difference Array Techniques

  • Prefix Sum: Query sum in range $[L, R]$ in $O(1)$ after $O(N)$ precomputation: $\text{sum}(L, R) = P[R] - P[L-1]$.
  • HashMap + Prefix Sum (Subarray Sum Equals K): Maintain running prefix sum `curr_sum`. If `curr_sum - K` exists in map, add its frequency count. Solves contiguous subarray sum in $O(N)$ time & $O(N)$ space.
  • Difference Array (Range Updates in $O(1)$): To add $V$ to all indices in $[L, R]$, set $D[L] \mathrel{+}= V$ and $D[R+1] \mathrel{-}= V$. Take prefix sum of $D$ at the end.
2

Classic Matrix In-Place Transformations

🔄 Rotate Image 90° Clockwise
Algorithm: 1. Transpose matrix ($M[i][j] \leftrightarrow M[j][i]$). 2. Reverse each row horizontally. Achieves $O(N^2)$ time, $O(1)$ in-place space!
🌀 Spiral Matrix Traversal
Maintain 4 boundaries: `top`, `bottom`, `left`, `right`. Traverse top row $\to$ right col $\to$ bottom row $\to$ left col, incrementing/decrementing bounds until crossed.
3

Code Template: Subarray Sum Equals K (C# & JavaScript)

💻 C# (.NET 8) Implementation
public int SubarraySum(int[] nums, int k) {
    var prefixMap = new Dictionary<int, int> { [0] = 1 };
    int currSum = 0, count = 0;
    foreach (int x in nums) {
        currSum += x;
        if (prefixMap.TryGetValue(currSum - k, out int freq)) {
            count += freq;
        }
        prefixMap[currSum] = prefixMap.GetValueOrDefault(currSum, 0) + 1;
    }
    return count;
}
4

Picture It: Prefix Sums & In-Place Rotation

nums 3 -1 4 2 5 01234 sum(1..3) = 5 P 0 3 2 6 8 13 P[4] − P[1] = 8 − 3 = 5 ✓ (one subtraction!)
Fig 3.1 — P has n+1 slots; P[0] = 0 kills the off-by-one
123 456 789 ① 147 258 369 ② 741 852 963 90° clockwise = ① transpose + ② reverse rows counter-clockwise = transpose + reverse columns
Fig 3.2 — two cheap passes, zero extra matrix

✏️ Dry run: SubarraySum([1, 2, 3], k = 3)

xcurrSumneed = currSum − kmap beforecount
11−2 ✗{0:1}0
230 ✓ (freq 1){0:1, 1:1}1 → [1,2]
363 ✓ (freq 1){0:1, 1:1, 3:1}2 → [3]
Bugs I keep making 🐞
  • Forgetting the seed `map[0] = 1` → misses subarrays that start at index 0
  • Using a sliding window when the array has negative numbers — the window invariant breaks; use prefix sum + map
  • Prefix sums overflowing `int` for $n = 10^5$, values $10^9$ → use `long`
🏋️ Practice set — tick them off
  • 303 · Range Sum Query Easy
  • 560 · Subarray Sum Equals K Med
  • 238 · Product of Array Except Self Med
  • 1094 · Car Pooling (difference array) Med
  • 48 · Rotate Image Med
  • 54 · Spiral Matrix Med
  • 49 · Group Anagrams Med
  • 128 · Longest Consecutive Sequence Med
  • 41 · First Missing Positive Hard

Two Pointers & Sliding Window Mastery

Convert nested $O(N^2)$ loops into blazing fast linear $O(N)$ passes
1

The 3 Two-Pointer Paradigms

1. Opposite Directional
`left = 0`, `right = N - 1`. Move inward based on target comparison.
2Sum II, 3Sum, Trapping Rain
2. Fast & Slow (Floyd's)
`slow = head`, `fast = head.next`. Move `fast` at 2x speed.
Cycle Detection, Middle of List
3. Sliding Window
`L = 0`, `R = 0`. Expand `R` to capture, shrink `L` to restore invariant.
Min Window, Longest Substring
🔍 Visualizing the Window Invariant: Expand R ➔ Shrink L
i=0
a
(past)
[
L ⬇
b
Window
i=2
c
Window
R ⬇
a
New Item
]
i=4
b
(unseen)
📏 Window Length: `R - L + 1` = 3 elements ⚠️ If duplicate found: jump `L` forward to `lastSeen[c] + 1`
📏 Window Length: `R - L + 1` = 3 elements ⚠️ If duplicate found: jump `L` forward to `lastSeen[c] + 1`
2

Universal Sliding Window Master Template

LengthOfLongestSubstring.cs — C# (.NET 8)
public int LengthOfLongestSubstring(string s) {
    var lastSeen = new Dictionary<char, int>();
    int left = 0, maxLen = 0;
    
    for (int right = 0; right < s.Length; right++) {
        char c = s[right];
        // Invariant Check: Shrink or jump left boundary if violated
        if (lastSeen.ContainsKey(c) && lastSeen[c] >= left) {
            left = lastSeen[c] + 1;
        }
        lastSeen[c] = right;
        maxLen = Math.Max(maxLen, right - left + 1);
    }
    return maxLen;
}
🎯 Key Takeaway

"Both pointers together visit each element at most TWICE ➔ Strict $O(N)$ Time!"

"Never write nested while loops with separate index resets — maintain the window invariant and slide forward." 😊

3

Opposite Pointers in Action: Trapping Rain Water

0 11 21 1 max = 3 L → ← R water[i] = min(maxLeft, maxRight) − h[i] total = 1 + 1 + 2 + 1 + 1 = 6 units move the side with the SMALLER max — it's the bottleneck for that cell
Fig 4.1 — heights [0,1,0,2,1,0,1,3,2,1,2,1] → 6 units, $O(n)$ time, $O(1)$ space

🔎 Trigger words

  • "sorted" + "pair/triplet" → opposite pointers
  • "contiguous" + "longest / shortest / at most K" → sliding window
  • "cycle", "middle", "k-th from end" → fast & slow

🪟 Window flavours

  • Fixed size k: add right, drop `i - k`
  • Variable: grow R, `while (invalid)` shrink L
  • "exactly K" = atMost(K) − atMost(K − 1)
Common slips
  • Shrinking with `if` instead of `while` — one shrink is rarely enough
  • Sliding window on arrays with negatives (sum isn't monotonic) → switch to prefix sums
  • 3Sum: forgetting to skip duplicates after a match → duplicate triplets
🏋️ Practice set
  • 167 · Two Sum II Med
  • 15 · 3Sum Med
  • 11 · Container With Most Water Med
  • 141 · Linked List Cycle Easy
  • 3 · Longest Substring w/o Repeat Med
  • 424 · Longest Repeating Char Replacement Med
  • 992 · Subarrays with K Distinct Hard
  • 42 · Trapping Rain Water Hard
  • 76 · Minimum Window Substring Hard

Custom Data Structures & LRU / LFU Cache

The #1 Tier 2 interview favorite: combine primitives to achieve strict $O(1)$ operations
1

LRU Cache Architecture: HashMap + Doubly Linked List

📐 Internal Architecture: HashMap + Doubly Linked List (DLL) All Operations $O(1)$
SENTINEL
dummy head
⇄
MOST RECENT
[K: 1, V: "A"]
⇄
IN-BETWEEN
[K: 2, V: "B"]
⇄
LEAST RECENT (LRU)
[K: 3, V: "C"]
⇄
SENTINEL
dummy tail
⚡ Get(k) / Put(k, v): Move node to head.next in $O(1)$ 🗑️ Evict on Full: Remove node before tail.prev in $O(1)$ 🗺️ HashMap: `map[key] ➔ Node` reference
2

Production-Grade C# LRU Cache Implementation

LRUCache.cs — Sentinel Nodes Pattern
public class LRUCache {
    private class Node {
        public int Key, Val;
        public Node Prev, Next;
        public Node(int k = 0, int v = 0) { Key = k; Val = v; }
    }

    private readonly int _cap;
    private readonly Dictionary<int, Node> _map;
    private readonly Node _head, _tail; // Dummy boundary sentinels

    public LRUCache(int capacity) {
        _cap = capacity;
        _map = new Dictionary<int, Node>();
        _head = new Node(); _tail = new Node();
        _head.Next = _tail; _tail.Prev = _head;
    }

    public int Get(int key) {
        if (!_map.TryGetValue(key, out var node)) return -1;
        Remove(node);
        InsertHead(node); // Mark as Most Recently Used
        return node.Val;
    }

    public void Put(int key, int value) {
        if (_map.TryGetValue(key, out var existing)) {
            Remove(existing);
        } else if (_map.Count == _cap) {
            var lru = _tail.Prev; // Evict least recently used
            Remove(lru);
            _map.Remove(lru.Key);
        }
        var fresh = new Node(key, value);
        InsertHead(fresh);
        _map[key] = fresh;
    }

    private void Remove(Node n) { n.Prev.Next = n.Next; n.Next.Prev = n.Prev; }
    private void InsertHead(Node n) {
        n.Next = _head.Next; n.Prev = _head;
        _head.Next.Prev = n; _head.Next = n;
    }
}
🎯 Key Takeaway

"Dummy Head & Tail sentinels eliminate 100% of null checks & edge case bugs in live interviews!"

"Never write special conditions for inserting into an empty list — sentinels guarantee head.Next and tail.Prev always exist." 😊

3

Other Must-Know Custom Data Structure Designs (Tier 2 Favorites)

🎲 Insert Delete GetRandom O(1)
Use `List<int>` for $O(1)$ random indexing + `Dictionary<int, int>` (val $\to$ index). On delete, swap target with last element in $O(1)$.
🐦 Design Twitter / News Feed
`Dictionary<int, List<Tweet>>` + `PriorityQueue<Tweet, int>` for K-way merging the recent tweets of followed users in $O(K \log F)$.
4

Trace It: LRU with capacity = 2

opreturnslist (MRU → LRU)note
put(1, A)—[1]insert at head
put(2, B)—[2, 1]cache now full
get(1)A[1, 2]hit → move 1 to head
put(3, C)—[3, 1]evict tail.Prev = 2
get(2)−1[3, 1]2 was evicted
5

LFU Cache: Frequency Buckets + minFreq Pointer

freqMap : freq → LRU list of nodes f = 1 k5 : E ⇄ k4 : D ← evict from here (LRU of min freq) f = 2 k2 : B f = 3 k1 : A minFreq = 1 get(k2) → unlink from f=2, push to head of f=3; if f=2 list empties and minFreq was 2 → minFreq++
Fig 5.1 — two maps: key → node and freq → DLL. Every op stays $O(1)$
Design-round slips
  • Evicting the node from the list but forgetting `_map.Remove(key)` → ghost entries
  • `Put` on an existing key that updates the value but doesn't bump recency/frequency
  • Not handling `capacity == 0` (LFU) — the first `Put` must be a no-op
  • On a new insert in LFU, forgetting to reset `minFreq = 1`
🏋️ Practice set
  • 206 · Reverse Linked List Easy
  • 21 · Merge Two Sorted Lists Easy
  • 155 · Min Stack Med
  • 146 · LRU Cache Med
  • 380 · Insert Delete GetRandom O(1) Med
  • 355 · Design Twitter Med
  • 138 · Copy List with Random Pointer Med
  • 460 · LFU Cache Hard
  • 432 · All O'one Data Structure Hard

Binary Search & Monotonic Answer Space

1

Binary Search Invariant Templates (C#)

  • Standard Invariant: `low = 0, high = N - 1`. While `low <= high`, `mid = low + (high - low) / 2` (prevents integer overflow in C#).
  • Rotated Sorted Array Search: At least one half (`[low, mid]` or `[mid, high]`) is always strictly sorted. Check if target lies in the sorted half to determine which boundary to discard.
2

Binary Search on Answer Space (`check(mid)` Framework)

When to use: "Find the Minimum X such that condition is satisfied"
If `check(mid)` is Monotonic (i.e. if feasible for $K$, then feasible for all values $> K$), we binary search directly over the range of possible answers $[1, \max(\text{values})]$ in $O(N \log(\text{Range}))$.
💻 C# Koko Eating Bananas / Ship Packages Master Template
public int MinEatingSpeed(int[] piles, int h) {
    bool CanFinish(int speed) {
        long totalHours = 0;
        foreach (int p in piles) {
            totalHours += (p + speed - 1L) / speed; // Ceiling division
        }
        return totalHours <= h;
    }

    int low = 1, high = piles.Max();
    int ans = high;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (CanFinish(mid)) {
            ans = mid;
            high = mid - 1; // Feasible! Try finding a smaller speed
        } else {
            low = mid + 1;  // Too slow, increase speed
        }
    }
    return ans;
}
3

The Mental Picture: find the first ✓ in F F F F ✓ ✓ ✓

speed k → canFinish(k) ✗ ✗ ✗ ✓ ✓ ✓ ✓ ✓ ✓ ✓ 123 456 78910 low mid high answer = first ✓ (boundary) ✓ at mid → keep it, go left ✗ at mid → discard, go right
Fig 6.1 — if the predicate flips exactly once, binary search works — no sorted array needed

✏️ Dry run: piles = [3, 6, 7, 11], h = 8

lowhighmidhours = Σ ⌈p / mid⌉≤ 8 ?action
11161+1+2+2 = 6✓ans = 6, high = 5
1531+2+3+4 = 10✗low = 4
4541+2+2+3 = 8✓ans = 4, high = 3
43low > high → stopreturn 4

🧭 Which loop?

  • `lo <= hi` + `ans` variable → safest, never infinite
  • `lo < hi` + `hi = mid` → lower-bound style, returns `lo`
  • Searching max-feasible? flip: `lo = mid` needs `mid = lo + (hi - lo + 1) / 2`

🎯 Answer-space smells

  • "minimum largest…", "maximum minimum…"
  • "within D days", "at most H hours"
  • huge answer range (10⁹) but cheap $O(n)$ check
Off-by-one graveyard
  • Starting `low = 0` for a speed/capacity → divide-by-zero inside `check`
  • `lo = mid` with floor-mid → infinite loop when `hi = lo + 1`
  • Rotated array: comparing with `nums[0]` instead of `nums[lo]` after narrowing
🏋️ Practice set
  • 704 · Binary Search Easy
  • 35 · Search Insert Position Easy
  • 74 · Search a 2D Matrix Med
  • 33 · Search in Rotated Sorted Array Med
  • 153 · Find Min in Rotated Array Med
  • 162 · Find Peak Element Med
  • 875 · Koko Eating Bananas Med
  • 1011 · Ship Packages in D Days Med
  • 410 · Split Array Largest Sum Hard
  • 4 · Median of Two Sorted Arrays Hard

Monotonic Stack, Deque & Priority Queues

1

Monotonic Stack: Next Greater Element in $O(N)$ (C#)

  • Concept: Maintain stack elements in strictly increasing or decreasing order. When a new element violates the monotonicity, pop elements and process their answers!
  • Key Applications: Daily Temperatures, Next Greater Element, Largest Rectangle in Histogram, Trapping Rain Water, Asteroid Collision.
💻 C# Daily Temperatures with Stack<int>
public int[] DailyTemperatures(int[] temperatures) {
    int n = temperatures.Length;
    var res = new int[n];
    var stack = new Stack<int>(); // Stores indices
    
    for (int i = 0; i < n; i++) {
        while (stack.Count > 0 && temperatures[i] > temperatures[stack.Peek()]) {
            int prevIdx = stack.Pop();
            res[prevIdx] = i - prevIdx;
        }
        stack.Push(i);
    }
    return res;
}
2

Two Heaps: Median from Data Stream (C# .NET 8 PriorityQueue)

Max-Heap (Left Half)
`PriorityQueue<int, int>` with negative priority for Max-Heap behavior. Root has maximum of smaller half.
Min-Heap (Right Half)
`PriorityQueue<int, int>` with natural priority. Root has minimum of larger half.
⚡ Median Invariant
Maintain size property: `maxHeap.Count == minHeap.Count` or `maxHeap.Count == minHeap.Count + 1`. Median is either `maxHeap.Peek()` or average of both roots in $O(1)$ time!
3

✏️ Dry run: DailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73])

itemppops (answer filled)stack after (idx:temp)
073—[0:73]
1740 → res[0] = 1[1:74]
2751 → res[1] = 1[2:75]
371—[2:75, 3:71]
469—[2:75, 3:71, 4:69]
5724 → 1, 3 → 2[2:75, 5:72]
6765 → 1, 2 → 4[6:76]
773—[6:76, 7:73]
↳ Result [1, 1, 4, 2, 1, 1, 0, 0] — the stack is always decreasing; every index is pushed once & popped once ⇒ $O(n)$
4

A Heap is Just an Array Wearing a Tree Costume

1 3 2 7 4 5 root = min · Peek O(1) backing array 1 3 2 7 4 5 012 345 children(i) = 2i + 1, 2i + 2 parent(i) = (i − 1) / 2 push: append + sift-up · pop: swap last to root + sift-down both O(log n) · heapify an array: O(n)
Fig 7.1 — complete binary tree ⇒ no pointers needed, perfect cache locality

🏆 Top-K trick

  • K largest → keep a min-heap of size K
  • pop when size > K ⇒ $O(n \log K)$, not $O(n \log n)$

🪟 Sliding window max

  • Deque of indices, values decreasing
  • Pop front if index left the window; pop back while smaller

🔀 K-way merge

  • Heap holds (value, listId, idx) — one head per list
  • Merge K sorted lists in $O(N \log K)$
🏋️ Practice set
  • 20 · Valid Parentheses Easy
  • 739 · Daily Temperatures Med
  • 496 · Next Greater Element I Easy
  • 215 · Kth Largest Element Med
  • 347 · Top K Frequent Elements Med
  • 621 · Task Scheduler Med
  • 84 · Largest Rectangle in Histogram Hard
  • 239 · Sliding Window Maximum Hard
  • 295 · Find Median from Data Stream Hard
  • 23 · Merge K Sorted Lists Hard

Trees, BST, LCA & Trie (Prefix Trees)

1

Tree DFS: Lowest Common Ancestor (C#)

💻 C# LCA in Binary Tree
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q) return root;
    var left = LowestCommonAncestor(root.left, p, q);
    var right = LowestCommonAncestor(root.right, p, q);
    if (left != null && right != null) return root; // Split point
    return left ?? right;
}
2

Trie (Prefix Tree) Master Template (C#)

💻 C# Trie Implementation
public class TrieNode {
    public Dictionary<char, TrieNode> Children = new();
    public bool IsWord = false;
}

public class Trie {
    private readonly TrieNode _root = new();

    public void Insert(string word) {
        var node = _root;
        foreach (char c in word) {
            if (!node.Children.ContainsKey(c)) node.Children[c] = new TrieNode();
            node = node.Children[c];
        }
        node.IsWord = true;
    }

    public bool StartsWith(string prefix) {
        var node = _root;
        foreach (char c in prefix) {
            if (!node.Children.TryGetValue(c, out node)) return false;
        }
        return true;
    }
}
3

See the Recursion: LCA Bubbling Up & a Trie of Words

3 5 1 6 2 0 8 7 4 left ≠ null && right ≠ null ⇒ me! returns 4 ↑ LCA(6, 4) = 5 · O(n) time, O(h) stack
Fig 8.1 — each call returns "the p/q I found below me"
root c a t r t d o g cat, car, cart, dog ● = IsWord "ca" shared → stored once
Fig 8.2 — lookup cost depends on word length $L$, not on how many words
💻 C# BFS Level-Order Template (Right Side View, Zigzag, Min Depth…)
public List<List<int>> LevelOrder(TreeNode root) {
    var res = new List<List<int>>();
    if (root == null) return res;
    var q = new Queue<TreeNode>();
    q.Enqueue(root);
    while (q.Count > 0) {
        int size = q.Count;          // freeze the level size first!
        var level = new List<int>(size);
        for (int i = 0; i < size; i++) {
            var node = q.Dequeue();
            level.Add(node.val);
            if (node.left != null) q.Enqueue(node.left);
            if (node.right != null) q.Enqueue(node.right);
        }
        res.Add(level);
    }
    return res;
}

🌳 Traversal cheat

  • Preorder → copy/serialize a tree
  • Inorder of a BST → sorted output
  • Postorder → "answer needs both children" (height, diameter, tree DP)
  • Levelorder → shortest depth, views

🧪 Validate BST

  • Pass bounds `(min, max)` down — comparing only with the parent is the classic bug
  • Use `long` bounds for `int.MinValue` nodes
🏋️ Practice set
  • 104 · Max Depth of Binary Tree Easy
  • 543 · Diameter of Binary Tree Easy
  • 102 · Level Order Traversal Med
  • 98 · Validate BST Med
  • 236 · LCA of Binary Tree Med
  • 230 · Kth Smallest in BST Med
  • 208 · Implement Trie Med
  • 124 · Binary Tree Max Path Sum Hard
  • 297 · Serialize / Deserialize Hard
  • 212 · Word Search II Hard

Graph Algorithms: BFS, DFS, TopoSort & DSU

1

Topological Sort (Kahn's In-Degree Algorithm in C#)

  • When to use: Build order, task scheduling with dependencies, course prerequisites, cycle detection in DAGs.
  • Algorithm: 1. Calculate in-degrees for all $V$ nodes. 2. Push nodes with `in_degree == 0` to `Queue<int>`. 3. While queue not empty, pop $u$, decrement neighbors' in-degree. If neighbor becomes 0, push to queue. If processed count $< V$, a cycle exists!
2

Union-Find (DSU) with Path Compression & Union by Size (C#)

💻 C# Disjoint Set Union O(α(N)) Template
public class UnionFind {
    private readonly int[] _parent;
    private readonly int[] _size;

    public UnionFind(int n) {
        _parent = new int[n];
        _size = new int[n];
        for (int i = 0; i < n; i++) { _parent[i] = i; _size[i] = 1; }
    }

    public int Find(int i) {
        if (_parent[i] != i) {
            _parent[i] = Find(_parent[i]); // Path compression
        }
        return _parent[i];
    }

    public bool Union(int i, int j) {
        int rootI = Find(i), rootJ = Find(j);
        if (rootI == rootJ) return false; // Cycle detected!
        if (_size[rootI] < _size[rootJ]) (rootI, rootJ) = (rootJ, rootI); // union by size
        _parent[rootJ] = rootI;
        _size[rootI] += _size[rootJ];
        return true;
    }
}
3

Dijkstra's Shortest Path Algorithm (C#)

  • Min-Heap PriorityQueue: Tracks `(node, dist)`. Initialize `dist[start] = 0`, all others $\infty$. Process min node, relax edges in $O((V + E) \log V)$ using `PriorityQueue<int, int>`. Note: Dijkstra fails on negative weight edges (use Bellman-Ford).
💻 C# Dijkstra with .NET 6+ PriorityQueue (lazy deletion)
public int[] Dijkstra(List<(int to, int w)>[] adj, int src) {
    var dist = new int[adj.Length];
    Array.Fill(dist, int.MaxValue);
    dist[src] = 0;
    var pq = new PriorityQueue<int, int>();   // (node, priority = dist)
    pq.Enqueue(src, 0);

    while (pq.TryDequeue(out int u, out int d)) {
        if (d > dist[u]) continue;           // stale entry — skip
        foreach (var (v, w) in adj[u]) {
            if (d + w < dist[v]) {
                dist[v] = d + w;                    // relax
                pq.Enqueue(v, dist[v]);
            }
        }
    }
    return dist;
}
4

Sketches: BFS Ripples & the DSU Forest

A B C D E F G dist: 1 · 2 · 3 first time you reach a node = shortest path (unweighted)
Fig 9.1 — BFS expands in rings; mark visited when enqueued
before Find(4) 0 1 2 4 path compression after Find(4) 0 1 2 4 everyone points at the root → next Find is ~O(1) (+ union by size keeps trees flat)
Fig 9.2 — amortized $O(\alpha(n))$ ≈ constant
🧭 Which graph algorithm? unweighted shortest → BFS · non-negative weights → Dijkstra · negative edges / ≤ K stops → Bellman-Ford · all-pairs, n ≤ 400 → Floyd-Warshall · dependencies → Topo sort · "are they connected?" (online) → DSU · cheapest wiring → Kruskal / Prim (MST)
Graph bugs that cost offers
  • Marking visited on dequeue instead of enqueue → the same node queued many times (TLE on grids)
  • Directed-graph cycle detection with a single `visited` set — you need 3 colours (white / grey / black)
  • Grid BFS: checking bounds after indexing → IndexOutOfRange
🏋️ Practice set
  • 200 · Number of Islands Med
  • 133 · Clone Graph Med
  • 994 · Rotting Oranges Med
  • 207 · Course Schedule Med
  • 210 · Course Schedule II Med
  • 684 · Redundant Connection Med
  • 743 · Network Delay Time Med
  • 787 · Cheapest Flights K Stops Med
  • 1584 · Min Cost to Connect Points Med
  • 127 · Word Ladder Hard
  • 269 · Alien Dictionary Hard

Dynamic Programming & Backtracking

1

The 5-Step DP Formulation Framework

1. State Definition
`dp[i][j]` = optimal answer for subarray $0 \dots i$ with constraint $j$.
2. Choice & Recurrence
Formulate transition: `dp[i] = min(dp[i - c] + 1)` (e.g. Coin Change).
3. Base Cases
Identify known starting values (e.g. `dp[0] = 0`, empty string states).
4. Rolling Array Optimization
If `dp[i]` only depends on `dp[i-1]`, reduce $O(N^2)$ space to $O(N)$!
5. Fill Order & Answer Cell
Iterate so every dependency is computed first (left→right, or backwards for 0/1 knapsack). Know where the answer lives: `dp[n]`, `dp[n][m]` or `max(dp)`.
2

Top 4 DP Problem Archetypes

Pattern Classic Problem State Transition
1D Subarray / Jump House Robber / Coin Change `dp[i] = max(dp[i-1], dp[i-2] + nums[i])`
2D Grid / Matrix Unique Paths / Edit Distance `dp[i][j] = dp[i-1][j] + dp[i][j-1]`
Two Strings / LCS Longest Common Subsequence If $s_1[i] == s_2[j] \implies dp[i-1][j-1] + 1$, else $\max(dp[i-1][j], dp[i][j-1])$
Knapsack 0/1 Partition Equal Subset Sum `dp[w] = dp[w] | dp[w - num]` (iterate backwards to avoid reuse)
3

Code Template: Coin Change 1D DP (C#)

💻 C# Bottom-Up 1D Array Dynamic Programming
public int CoinChange(int[] coins, int amount) {
    var dp = new int[amount + 1];
    Array.Fill(dp, amount + 1); // Sentinel max value
    dp[0] = 0;
    
    for (int a = 1; a <= amount; a++) {
        foreach (int c in coins) {
            if (a - c >= 0) {
                dp[a] = Math.Min(dp[a], dp[a - c] + 1);
            }
        }
    }
    return dp[amount] > amount ? -1 : dp[amount];
}
4

Why Memoization Works: the Recursion Tree Collapses

f(5) f(4) f(3) f(3) f(2) f(2) f(1) f(2) f(1) memo hit → O(1) pruned subtree without memo: ~2ⁿ calls · with memo: n distinct states time = #states × work per state = O(n) × O(1)
Fig 10.1 — overlapping subproblems + optimal substructure = DP. Crossed boxes are cache hits

✏️ Fill the table: LCS("abcde", "ace") = 3

""abcde
""000000
a01 ↘1111
c0112 ↘22
e011223 ↘
✎ Green ↘ = characters match → take diagonal + 1. Otherwise copy the bigger of ← and ↑. Only the previous row is ever read ⇒ roll it into one array.

🔁 Top-down or bottom-up?

  • Interview: start top-down + memo — easiest to get right
  • Convert to bottom-up when asked about stack depth or space

🧩 State-design hint

  • "What do I need to know to make the remaining decisions?" → that's your state
  • index + capacity, i + j, mask, (pos, holding-stock)…
🏋️ Practice set (backtracking lives on page 13 ➜)
  • 70 · Climbing Stairs Easy
  • 198 · House Robber Med
  • 322 · Coin Change Med
  • 300 · Longest Increasing Subsequence Med
  • 1143 · Longest Common Subsequence Med
  • 416 · Partition Equal Subset Sum Med
  • 139 · Word Break Med
  • 62 · Unique Paths Med
  • 72 · Edit Distance Hard
  • 312 · Burst Balloons Hard

Intervals, Greedy & Bitwise / Concurrency

1

Intervals Master Framework: Sort by Start Time

  • Merge Overlapping Intervals: Sort intervals by `start`. Iterate through list: if `curr.start <= prev.end`, merge by updating `prev.end = max(prev.end, curr.end)`. Otherwise append new interval.
  • Meeting Rooms II (Min Conference Rooms): Min-Heap of end times. Sort meetings by start time. If `start >= heap.peek()`, pop room (reused). Push current end time. `len(heap)` is the room count!
2

Bit Manipulation Ninja Tricks

XOR Cancellation
$x \oplus x = 0$, $x \oplus 0 = x$. Solves Single Number in $O(N)$ time & $O(1)$ space.
Clear Lowest Set Bit
`n & (n - 1)` removes the lowest set bit. Counts set bits (Hamming weight) in $O(\text{set bits})$.
Power of Two Check
`n > 0 and (n & (n - 1)) == 0` checks if $n$ is a power of 2 in $O(1)$!
3

Thread-Safe Data Structures (C# Senior / Tier 2 Focus)

💻 C# Thread-Safe Bounded Blocking Queue
public class BoundedBlockingQueue {
    private readonly Queue<int> _queue = new();
    private readonly int _capacity;
    private readonly object _lock = new();

    public BoundedBlockingQueue(int capacity) { _capacity = capacity; }

    public void Enqueue(int element) {
        lock (_lock) {
            while (_queue.Count == _capacity) {
                Monitor.Wait(_lock); // Handle spurious wakeups
            }
            _queue.Enqueue(element);
            Monitor.PulseAll(_lock);
        }
    }

    public int Dequeue() {
        lock (_lock) {
            while (_queue.Count == 0) {
                Monitor.Wait(_lock);
            }
            int item = _queue.Dequeue();
            Monitor.PulseAll(_lock);
            return item;
        }
    }
}
4

Merge Intervals on a Number Line

1368101518 [1,3] [2,6] [8,10] [15,18] 2 ≤ 3 → overlap! [1, 6] [8,10] [15,18] ① sort by start ② if start ≤ last.end → extend ③ else push new interval result: O(n log n)
Fig 11.1 — after sorting, only the last merged interval can overlap the next one
5

Greedy: When Is "Take the Best Now" Safe?

🦘 Jump Game
Track `farthest = max(farthest, i + nums[i])`. If `i > farthest` you're stuck. $O(n)$.
⛽ Gas Station
If total gas ≥ total cost an answer exists; reset start whenever the running tank goes negative.
📅 Activity Selection
Sort by end time, always keep the meeting that frees the room earliest (Non-overlapping Intervals).
🧠 Proof sketch to say out loud: "Exchange argument — take any optimal answer; swapping its first choice for my greedy choice never makes it worse, so greedy is optimal." If you can't argue that, it's probably DP.
🏋️ Practice set
  • 136 · Single Number Easy
  • 191 · Number of 1 Bits Easy
  • 56 · Merge Intervals Med
  • 57 · Insert Interval Med
  • 435 · Non-overlapping Intervals Med
  • 253 · Meeting Rooms II Med
  • 55 · Jump Game Med
  • 134 · Gas Station Med
  • 763 · Partition Labels Med
  • 1114 · Print in Order (concurrency) Easy
  • 1188 · Bounded Blocking Queue Med

Tier 1, 2, 3 Rubrics & Live Interview Execution

1

The 6-Step Live Interview Protocol

Step 1: Clarify Constraints
Array bounds, negative values, duplicates, memory limits, edge cases (empty list, 1 element).
Step 2: Propose Naive & Optimal
State brute-force ($O(N^2)$), then introduce $O(N \log N)$ or $O(N)$ with data structure rationale.
Step 3: State Big-O First
State Time and Space complexity upfront to get interviewer nod before writing code!
Step 4: Clean Production Code
Write clean, idiomatic code with helper functions, meaningful variable names, and early guards.
Step 5: Systematic Dry Run
Trace pointers (`L`, `R`, `mid`, `stack`) with a small table against a sample input. Catch bugs yourself!
Step 6: Follow-up Scale
Explain streaming data handling, disk spilling, and distributed parallelization.
2

Top 10 Senior Red Flags to Avoid in Coding Rounds

  • ❌ Jumping straight into code without explaining your approach or confirming alignment.
  • ❌ Coding in complete silence for 10 minutes without thinking aloud.
  • ❌ Using cryptic 1-letter variables ($a, b, c, x, y$) instead of clean domain names (`left_max`, `in_degree`).
  • ❌ Ignoring interviewer hints — hints are deliberate alignment tests, not deductions.
  • ❌ Saying "My code works!" without running a structured manual dry-run trace.
3

How the Interviewer's Scorecard Actually Looks

dimension no hireleanstrong hire 🗣️ Communication 🧩 Problem solving 🧼 Code quality 🧪 Verification senior bar dry-run here!
Fig 12.1 — most seniors lose points on verification, not on the algorithm

💬 Say this at minute 2

  • "Can the input be empty? Negative? Duplicates?"
  • "Let me write two quick examples, including an edge case."

💬 Say this before coding

  • "Brute force is $O(n^2)$; with a hashmap I can get $O(n)$ time, $O(n)$ space. Shall I go with that?"

💬 Say this when stuck

  • "Let me try a smaller input by hand and look for the repeated work."
  • "If it were sorted, what would change?"
🎯 Final Takeaway for 8+ YoE Candidates
Seniors are hired for sound engineering judgment, code clarity, and architectural composure under pressure. Master these 15 core patterns, communicate with confidence, and crush your interviews across all tiers!

Backtracking & Recursion Trees

One template solves subsets, combinations, permutations, N-Queens & word search
1

Draw the Decision Tree First — Subsets of [1, 2, 3]

[ ] [1] [2] [3] [1,2] [1,3] [2,3] [1,2,3] i=0i=1i=2 every node = one answer → 2³ = 8 children only pick indices > start ⇒ no duplicates like [2,1] no children: nothing after 3
Fig 13.1 — depth = path length, branching = remaining choices · time ≈ #nodes × cost to copy
2

The Universal Backtracking Template (C#)

Backtrack.cs — choose / explore / un-choose
public IList<IList<int>> SubsetsWithDup(int[] nums) {
    Array.Sort(nums);                                 // sort so duplicates sit together
    var res = new List<IList<int>>();
    var path = new List<int>();

    void Backtrack(int start) {
        res.Add(new List<int>(path));             // 1. record (copy!)
        for (int i = start; i < nums.Length; i++) {
            if (i > start && nums[i] == nums[i - 1]) continue; // 2. prune dup branch
            path.Add(nums[i]);                        // 3. choose
            Backtrack(i + 1);                         // 4. explore (i to allow reuse)
            path.RemoveAt(path.Count - 1);            // 5. un-choose
        }
    }

    Backtrack(0);
    return res;
}
3

Same Skeleton, Different Knobs

Problem familyLoop starts atRecord whenExtra stateSize of tree
Subsets`start`, recurse `i + 1`every node—$O(2^n)$
Combination Sum`start`, recurse `i` (reuse)`remain == 0`remaining targetexponential, prune `remain < 0`
Permutations`0` every time`path.Count == n``bool[] used`$O(n!)$
N-Queensrow by row`row == n`cols, diag `r-c`, anti-diag `r+c` sets$O(n!)$
Word Search (grid)4 neighbours`k == word.Length`mark cell `'#'`, restore after$O(m n \cdot 4^L)$

✂️ Pruning = speed

  • Sort first, then `break` (not `continue`) once a candidate exceeds the target
  • Check validity before recursing, not after

🐞 Classic bug

  • `res.Add(path)` without copying → every answer ends up as the same empty list

🔁 DP or backtracking?

  • "count / best" → usually DP
  • "list all" → backtracking (output is exponential anyway)
🏋️ Practice set
  • 78 · Subsets Med
  • 90 · Subsets II Med
  • 39 · Combination Sum Med
  • 40 · Combination Sum II Med
  • 46 · Permutations Med
  • 17 · Letter Combinations of a Phone Med
  • 22 · Generate Parentheses Med
  • 79 · Word Search Med
  • 131 · Palindrome Partitioning Med
  • 51 · N-Queens Hard
  • 37 · Sudoku Solver Hard

"Which Pattern?" Flowchart & Revision Sheet

Ask these questions in order — the first "yes" is usually the intended pattern
1

The Pattern Picker

📥 Read constraints → estimate target Big-O Sorted input, or answer is monotonic? yes Binary Search · Two Pointers no Contiguous subarray / substring? yes Sliding Window · Prefix Sum + Map no Top-K, k-th, median, merge K lists? yes Heap / PriorityQueue no Next greater / smaller, span, histogram? yes Monotonic Stack / Deque no Tree, graph, grid or dependencies? yes DFS/BFS · Topo · DSU · Dijkstra no Generate ALL combos / permutations? yes Backtracking + pruning no Min/max/count with repeating choices? yes Dynamic Programming no Intervals, meetings, scheduling? yes Sort + Sweep · Min-Heap of ends still nothing? → HashMap + brute force first, then optimise the repeated work 🙂
Fig 14.1 — print this, stick it above your desk
2

One-Line Template Revision Sheet

PatternCore move (say it in one breath)TimePage
Prefix Sum + Mapcount of `sum - k` seen so far; seed `{0: 1}`$O(n)$3
Sliding Windowgrow R, `while` invalid shrink L, update answer$O(n)$4
Two Pointersmove the pointer whose side can't improve the answer$O(n)$4
LRU Cachemap key→node + DLL with sentinels; move to head on touch$O(1)$5
Binary Search on Answermonotonic `check(mid)`; ✓ → go left & save$O(n \log R)$6
Monotonic Stackpop while current beats top; popped item's answer = current$O(n)$7
Top-K Heapmin-heap of size K, pop when larger$O(n \log k)$7
Tree DFS"what do I return to my parent?"$O(n)$8
BFSqueue + visited on enqueue; level = freeze `q.Count`$O(V + E)$9
Topo Sortqueue all in-degree 0; processed < V ⇒ cycle$O(V + E)$9
DSUfind with path compression, union by size$O(\alpha(n))$9
DPstate → recurrence → base → order → answer cellstates × work10
Backtrackingrecord, loop choices, choose / explore / un-chooseexponential13
Intervalssort by start; merge if `start ≤ last.end`$O(n \log n)$11
🌙 Night-Before Checklist
✓ Re-type LRU, DSU, Dijkstra and the backtracking template from memory once. ✓ Skim your pattern journal, not new problems. ✓ Sleep — a rested brain debugs faster than a crammed one.
📖 DSA Master Table of Contents