Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
Short answer: Kadane’s algorithm: keep a running sum; if it goes negative, reset to 0 (or start fresh at the next element). Track the best running sum seen. This finds the contiguous subarray with maximum sum in O(n). Pr…
Short answer: Build prefix products from the left and suffix products from the right. For index i, answer[i] = prefix[i] * suffix[i]. You can do it with one output array and one running suffix to achieve O(1) extra space…
Short answer: Sort the array. Fix one number, then use two pointers on the remainder to find pairs that sum to −fixed. Skip duplicates carefully to return unique triplets. Overall O(n²). Interview approach Sort ascending…
Short answer: Two pointers at both ends. Area = min(height[L], height[R]) * (R − L). Move the pointer at the shorter line inward, because width shrinks and only a taller line can improve area. O(n) time. Complexity Time…
Short answer: Sliding window with a map/set of characters in the current window. Expand right; when a duplicate appears, shrink left until the window is unique again. Track max window length. Sample solution C# int Lengt…
Short answer: Each node must lie within an allowed (low, high) range. Recurse left with high = node.val and right with low = node.val. Alternatively, inorder traversal must produce a strictly increasing sequence. Complex…
Short answer: Scan the grid. When you find a '1', increment island count and DFS/BFS to sink (mark visited) the entire connected land component. Count how many times you start a flood fill. Complexity Time O(rows * cols)…
Short answer: Model prerequisites as a directed graph. Detect a cycle with DFS colors (white/gray/black) or Kahn’s algorithm (BFS indegrees). If a cycle exists, you cannot finish all courses. Complexity Time O(V + E), Sp…
Short answer: Unbounded knapsack DP: dp[a] = minimum coins to make amount a. For each coin, update dp[x] = min(dp[x], dp[x - coin] + 1). Initialize dp[0] = 0 and others to +∞. Return -1 if unreachable. Complexity Time O(…
Short answer: Sort intervals by start. Scan and merge when the next start ≤ current end; otherwise push current and start a new one. O(n log n) from sorting. Sample solution C# int[][] Merge(int[][] intervals) { Array.So…
Short answer: Modified binary search: check which half is sorted, then decide whether the target lies in that sorted half. Still O(log n). Interview approach Compute mid. If left half sorted (nums[lo] ≤ nums[mid]): if ta…
Short answer: DFS from each cell matching the first letter. Mark visited, explore 4 directions for the next character, then unmark (backtrack). Return true as soon as the word is completed. Complexity Time roughly O(N *…
Short answer: Each node has children map/array[26] and an isEnd flag. insert/search/startsWith walk character by character. Tries shine for autocomplete and dictionary prefix queries. Complexity Time O(L) per operation (…
Short answer: Prioritize: Arrays/Hashing, Two Pointers, Sliding Window, Binary Search, Stack, Linked List, Trees (BFS/DFS), Graphs (BFS/DFS/topo), Heaps, Intervals, 1-D DP, Backtracking, and LRU-style design. Pattern rec…
Short answer: Two pointers with a gap of n. Advance fast n steps, then move both until fast hits the end; slow.next is the node to delete. One pass, O(1) space. Edge cases to mention Remove head (n == length) Single node…
Short answer: BFS with a queue. Process level size at a time, enqueue children, and collect values per level into a list of lists. Complexity Time O(n), Space O(n) for the queue/result. Common follow-ups Zigzag level ord…
Short answer: BST: walk from root — if both values are smaller go left, both larger go right, else current is LCA. General binary tree: recurse; if both sides return non-null, current is LCA; else return the non-null sid…
Short answer: Count frequencies with a hash map. Then either use a min-heap of size k (O(n log k)) or bucket sort by frequency (O(n)) since frequencies are in 1..n. Complexity Heap O(n log k); bucket O(n). Common follow-…
Short answer: BFS/DFS while maintaining a map from original node → clone. For each neighbor, clone if missing, then link clones. Prevents infinite loops on cycles. Complexity Time O(V + E), Space O(V). The visited/clone…
Short answer: Min-heap of size k: O(n log k). Quickselect (partition) average O(n), worst O(n²). Sorting is O(n log n) — mention then improve. Common follow-ups Kth largest in a stream Find median If they care about wors…
Short answer: Transpose the matrix, then reverse each row (for 90° clockwise). Alternatively rotate layer-by-layer swapping four cells. Both are O(n²) time and O(1) extra space. Transpose + reverse is easier to get right…
Short answer: Diameter is the longest path between any two nodes (edges count). DFS returns height; at each node update global max of leftHeight + rightHeight. O(n). Path may not pass through the root — that is the commo…
Short answer: Keep a normal stack plus an auxiliary stack of current minima (or store pairs). push/pop/top/getMin all O(1). On push, push min(x, currentMin) onto the min stack. Complexity All operations O(1), Space O(n).…
Short answer: Subsets: at each index choose include/exclude (or loop-based cascading). Permutations: swap/choose unused elements recursively. Always discuss time complexity exponential in n and when to prune. Complexity…
Short answer: DFS while tracking parent: visiting an already-visited neighbor that is not the parent means a cycle. Union-Find (Disjoint Set) also works for edge lists: union fails if both ends share a parent. Complexity…
DSA & Coding Interviews Coding Interview FAQ · Arrays & DP
Short answer: Kadane’s algorithm: keep a running sum; if it goes negative, reset to 0 (or start fresh at the next element). Track the best running sum seen. This finds the contiguous subarray with maximum sum in O(n).
Given an integer array, find the contiguous subarray with the largest sum and return that sum.
int MaxSubArray(int[] nums) {
int best = nums[0], cur = nums[0];
for (int i = 1; i < nums.Length; i++) {
cur = Math.Max(nums[i], cur + nums[i]);
best = Math.Max(best, cur);
}
return best;
}
Time O(n), Space O(1).
If the interviewer allows empty subarray, resetting to 0 is fine; otherwise use the version above.
DSA & Coding Interviews Coding Interview FAQ · Arrays & Prefix
Short answer: Build prefix products from the left and suffix products from the right. For index i, answer[i] = prefix[i] * suffix[i]. You can do it with one output array and one running suffix to achieve O(1) extra space (excluding output).
int[] ProductExceptSelf(int[] nums) {
int n = nums.Length;
var ans = new int[n];
ans[0] = 1;
for (int i = 1; i < n; i++) ans[i] = ans[i - 1] * nums[i - 1];
int right = 1;
for (int i = n - 1; i >= 0; i--) {
ans[i] *= right;
right *= nums[i];
}
return ans;
}
Time O(n), Space O(1) extra (output not counted).
Never use division in the interview version — many panels explicitly forbid it.
DSA & Coding Interviews Coding Interview FAQ · Two Pointers
Short answer: Sort the array. Fix one number, then use two pointers on the remainder to find pairs that sum to −fixed. Skip duplicates carefully to return unique triplets. Overall O(n²).
Time O(n²), Space O(1) extra besides output (sorting may use O(log n)).
Sorting + two pointers is the pattern interviewers expect after Two Sum.
DSA & Coding Interviews Coding Interview FAQ · Two Pointers
Short answer: Two pointers at both ends. Area = min(height[L], height[R]) * (R − L). Move the pointer at the shorter line inward, because width shrinks and only a taller line can improve area. O(n) time.
Time O(n), Space O(1).
Prove the greedy move: the shorter side is the bottleneck.
DSA & Coding Interviews Coding Interview FAQ · Sliding Window
Short answer: Sliding window with a map/set of characters in the current window. Expand right; when a duplicate appears, shrink left until the window is unique again. Track max window length.
int LengthOfLongestSubstring(string s) {
var last = new Dictionary<char, int>();
int left = 0, best = 0;
for (int right = 0; right < s.Length; right++) {
char c = s[right];
if (last.TryGetValue(c, out int prev) && prev >= left)
left = prev + 1;
last[c] = right;
best = Math.Max(best, right - left + 1);
}
return best;
}
Time O(n), Space O(min(n, alphabet)).
Name the pattern “variable-size sliding window” — it signals seniority.
DSA & Coding Interviews Coding Interview FAQ · Trees
Short answer: Each node must lie within an allowed (low, high) range. Recurse left with high = node.val and right with low = node.val. Alternatively, inorder traversal must produce a strictly increasing sequence.
Time O(n), Space O(h) recursion height.
Pass long.MinValue/MaxValue (or nullable bounds) to avoid int overflow edge cases.
DSA & Coding Interviews Coding Interview FAQ · Graphs / Grid DFS
Short answer: Scan the grid. When you find a '1', increment island count and DFS/BFS to sink (mark visited) the entire connected land component. Count how many times you start a flood fill.
Time O(rows * cols), Space O(rows * cols) worst-case recursion/queue.
Clarify 4-direction vs 8-direction before coding.
DSA & Coding Interviews Coding Interview FAQ · Graphs
Short answer: Model prerequisites as a directed graph. Detect a cycle with DFS colors (white/gray/black) or Kahn’s algorithm (BFS indegrees). If a cycle exists, you cannot finish all courses.
Time O(V + E), Space O(V + E).
Say “topological sort / cycle detection” early — that is the pattern name they want.
DSA & Coding Interviews Coding Interview FAQ · Dynamic Programming
Short answer: Unbounded knapsack DP: dp[a] = minimum coins to make amount a. For each coin, update dp[x] = min(dp[x], dp[x - coin] + 1). Initialize dp[0] = 0 and others to +∞. Return -1 if unreachable.
Time O(amount * coins), Space O(amount).
Mention top-down memoization as an alternative to bottom-up.
DSA & Coding Interviews Coding Interview FAQ · Intervals
Short answer: Sort intervals by start. Scan and merge when the next start ≤ current end; otherwise push current and start a new one. O(n log n) from sorting.
int[][] Merge(int[][] intervals) {
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
var res = new List<int[]>();
foreach (var iv in intervals) {
if (res.Count == 0 || res[^1][1] < iv[0]) res.Add(iv);
else res[^1][1] = Math.Max(res[^1][1], iv[1]);
}
return res.ToArray();
}
Time O(n log n), Space O(n).
Sorting by start is non-negotiable — say it before coding.
DSA & Coding Interviews Coding Interview FAQ · Binary Search
Short answer: Modified binary search: check which half is sorted, then decide whether the target lies in that sorted half. Still O(log n).
Time O(log n), Space O(1).
Draw a rotated array and mark the sorted half each step while explaining.
DSA & Coding Interviews Coding Interview FAQ · Backtracking
Short answer: DFS from each cell matching the first letter. Mark visited, explore 4 directions for the next character, then unmark (backtrack). Return true as soon as the word is completed.
Time roughly O(N * 4^L) worst case (N cells, L word length); Space O(L) recursion.
Emphasize marking/unmarking — that is the backtracking signature.
DSA & Coding Interviews Coding Interview FAQ · Tries
Short answer: Each node has children map/array[26] and an isEnd flag. insert/search/startsWith walk character by character. Tries shine for autocomplete and dictionary prefix queries.
Time O(L) per operation (L = word length), Space O(total characters).
Ask if alphabet is lowercase English — array[26] is cleaner than Dictionary.
DSA & Coding Interviews Coding Interview FAQ · Interview Strategy
Short answer: Prioritize: Arrays/Hashing, Two Pointers, Sliding Window, Binary Search, Stack, Linked List, Trees (BFS/DFS), Graphs (BFS/DFS/topo), Heaps, Intervals, 1-D DP, Backtracking, and LRU-style design. Pattern recognition beats memorizing hundreds of problems.
Depth on patterns beats shallow volume. Quality reps with explanation win offers.
DSA & Coding Interviews Coding Interview FAQ · Linked Lists
Short answer: Two pointers with a gap of n. Advance fast n steps, then move both until fast hits the end; slow.next is the node to delete. One pass, O(1) space.
Use a dummy head so deleting the real head is uniform.
DSA & Coding Interviews Coding Interview FAQ · Trees
Short answer: BFS with a queue. Process level size at a time, enqueue children, and collect values per level into a list of lists.
Time O(n), Space O(n) for the queue/result.
Capturing level size before the inner loop is the key detail interviewers watch for.
DSA & Coding Interviews Coding Interview FAQ · Trees
Short answer: BST: walk from root — if both values are smaller go left, both larger go right, else current is LCA. General binary tree: recurse; if both sides return non-null, current is LCA; else return the non-null side.
BST average O(h); general tree O(n).
Ask which tree type — the optimal approach changes.
DSA & Coding Interviews Coding Interview FAQ · Heap / Bucket Sort
Short answer: Count frequencies with a hash map. Then either use a min-heap of size k (O(n log k)) or bucket sort by frequency (O(n)) since frequencies are in 1..n.
Heap O(n log k); bucket O(n).
Prefer bucket sort when you want to show O(n) mastery.
DSA & Coding Interviews Coding Interview FAQ · Graphs
Short answer: BFS/DFS while maintaining a map from original node → clone. For each neighbor, clone if missing, then link clones. Prevents infinite loops on cycles.
Time O(V + E), Space O(V).
The visited/clone map is mandatory — say it before writing loops.
DSA & Coding Interviews Coding Interview FAQ · Heap / Quickselect
Short answer: Min-heap of size k: O(n log k). Quickselect (partition) average O(n), worst O(n²). Sorting is O(n log n) — mention then improve.
If they care about worst-case, discuss heap; if average-case, mention Quickselect.
DSA & Coding Interviews Coding Interview FAQ · Matrices
Short answer: Transpose the matrix, then reverse each row (for 90° clockwise). Alternatively rotate layer-by-layer swapping four cells. Both are O(n²) time and O(1) extra space.
Transpose + reverse is easier to get right under pressure.
DSA & Coding Interviews Coding Interview FAQ · Trees
Short answer: Diameter is the longest path between any two nodes (edges count). DFS returns height; at each node update global max of leftHeight + rightHeight. O(n).
Path may not pass through the root — that is the common trap.
DSA & Coding Interviews Coding Interview FAQ · Stacks / Design
Short answer: Keep a normal stack plus an auxiliary stack of current minima (or store pairs). push/pop/top/getMin all O(1). On push, push min(x, currentMin) onto the min stack.
All operations O(1), Space O(n).
Do not scan the stack for getMin — that is O(n) and fails the prompt.
DSA & Coding Interviews Coding Interview FAQ · Backtracking
Short answer: Subsets: at each index choose include/exclude (or loop-based cascading). Permutations: swap/choose unused elements recursively. Always discuss time complexity exponential in n and when to prune.
Subsets O(n * 2^n); Permutations O(n * n!).
Draw the decision tree for n=3 — it proves you understand recursion depth.
DSA & Coding Interviews Coding Interview FAQ · Graphs
Short answer: DFS while tracking parent: visiting an already-visited neighbor that is not the parent means a cycle. Union-Find (Disjoint Set) also works for edge lists: union fails if both ends share a parent.
Time O(V + E).
Do not reuse the directed-graph “gray node” story without adjusting for parent.