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!
✍️ Notes by Amit Mahata • Staff Engineer SeriesPage 03 / 14
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 intSubarraySum(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
Fig 3.1 — P has n+1 slots; P[0] = 0 kills the off-by-oneFig 3.2 — two cheap passes, zero extra matrix
✏️ Dry run: SubarraySum([1, 2, 3], k = 3)
x
currSum
need = currSum − k
map before
count
1
1
−2 ✗
{0:1}
0
2
3
0 ✓ (freq 1)
{0:1, 1:1}
1 → [1,2]
3
6
3 ✓ (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
Slide 04/14✍️ @amitmahata • Staff Series
Pointers & Windows ⚡
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 intLengthOfLongestSubstring(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 violatedif (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
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
⚡ Sliding Window Meta✍️ Follow @amitmahata🔖 Save for later!
Slide 05/14✍️ @amitmahata • Staff Series
Custom DS Design 🏗️
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 classLRUCache {
private classNode {
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 sentinelspublic LRUCache(int capacity) {
_cap = capacity;
_map = new Dictionary<int, Node>();
_head = new Node(); _tail = new Node();
_head.Next = _tail; _tail.Prev = _head;
}
public intGet(int key) {
if (!_map.TryGetValue(key, out var node)) return -1;
Remove(node);
InsertHead(node); // Mark as Most Recently Usedreturn node.Val;
}
public voidPut(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 voidRemove(Node n) { n.Prev.Next = n.Next; n.Next.Prev = n.Prev; }
private voidInsertHead(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." 😊
🏗️ Custom DS Design✍️ Follow @amitmahata🔖 Save for later!
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
op
returns
list (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
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
✍️ Notes by Amit Mahata • Staff Engineer SeriesPage 06 / 14
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 intMinEatingSpeed(int[] piles, int h) {
boolCanFinish(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 ✓ ✓ ✓
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
low
high
mid
hours = Σ ⌈p / mid⌉
≤ 8 ?
action
1
11
6
1+1+2+2 = 6
✓
ans = 6, high = 5
1
5
3
1+2+3+4 = 10
✗
low = 4
4
5
4
1+2+2+3 = 8
✓
ans = 4, high = 3
4
3
low > high → stop
return 4
🧭 Which loop?
`lo <= hi` + `ans` variable → safest, never infinite
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
✍️ Notes by Amit Mahata • Staff Engineer SeriesPage 07 / 14
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 indicesfor (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!
↳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
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
✍️ Notes by Amit Mahata • Staff Engineer SeriesPage 08 / 14
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 pointreturn left ?? right;
}
2
Trie (Prefix Tree) Master Template (C#)
💻 C# Trie Implementation
public classTrieNode {
public Dictionary<char, TrieNode> Children = new();
public bool IsWord = false;
}
public classTrie {
private readonly TrieNode _root = new();
public voidInsert(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 boolStartsWith(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
Fig 8.1 — each call returns "the p/q I found below me"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
✍️ Notes by Amit Mahata • Staff Engineer SeriesPage 09 / 14
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 classUnionFind {
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 intFind(int i) {
if (_parent[i] != i) {
_parent[i] = Find(_parent[i]); // Path compression
}
return _parent[i];
}
public boolUnion(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 — skipforeach (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
Fig 9.1 — BFS expands in rings; mark visited when enqueuedFig 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
✍️ Notes by Amit Mahata • Staff Engineer SeriesPage 10 / 14
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$.
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)`.
public intCoinChange(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
✎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
✍️ Notes by Amit Mahata • Staff Engineer SeriesPage 11 / 14
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 classBoundedBlockingQueue {
private readonly Queue<int> _queue = new();
private readonly int _capacity;
private readonly object _lock = new();
public BoundedBlockingQueue(int capacity) { _capacity = capacity; }
public voidEnqueue(int element) {
lock (_lock) {
while (_queue.Count == _capacity) {
Monitor.Wait(_lock); // Handle spurious wakeups
}
_queue.Enqueue(element);
Monitor.PulseAll(_lock);
}
}
public intDequeue() {
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
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
✍️ Notes by Amit Mahata • Staff Engineer SeriesPage 12 / 14
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
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!
Slide 13/14✍️ @amitmahata • Staff Series
Choose · Explore · Un-choose 🌲
Backtracking & Recursion Trees
One template solves subsets, combinations, permutations, N-Queens & word search
1
Draw the Decision Tree First — Subsets of [1, 2, 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 togethervar res = new List<IList<int>>();
var path = new List<int>();
voidBacktrack(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 family
Loop starts at
Record when
Extra state
Size of tree
Subsets
`start`, recurse `i + 1`
every node
—
$O(2^n)$
Combination Sum
`start`, recurse `i` (reuse)
`remain == 0`
remaining target
exponential, prune `remain < 0`
Permutations
`0` every time
`path.Count == n`
`bool[] used`
$O(n!)$
N-Queens
row 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
🌲 Backtracking Template✍️ Follow @amitmahata🔖 Save for later!
Slide 14/14✍️ @amitmahata • Staff Series
Night-Before Revision 🌙
"Which Pattern?" Flowchart & Revision Sheet
Ask these questions in order — the first "yes" is usually the intended pattern
1
The Pattern Picker
Fig 14.1 — print this, stick it above your desk
2
One-Line Template Revision Sheet
Pattern
Core move (say it in one breath)
Time
Page
Prefix Sum + Map
count of `sum - k` seen so far; seed `{0: 1}`
$O(n)$
3
Sliding Window
grow R, `while` invalid shrink L, update answer
$O(n)$
4
Two Pointers
move the pointer whose side can't improve the answer
$O(n)$
4
LRU Cache
map key→node + DLL with sentinels; move to head on touch
$O(1)$
5
Binary Search on Answer
monotonic `check(mid)`; ✓ → go left & save
$O(n \log R)$
6
Monotonic Stack
pop while current beats top; popped item's answer = current
$O(n)$
7
Top-K Heap
min-heap of size K, pop when larger
$O(n \log k)$
7
Tree DFS
"what do I return to my parent?"
$O(n)$
8
BFS
queue + visited on enqueue; level = freeze `q.Count`
✓ 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.