Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
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: Valid Anagram: count character frequencies (or sort both strings). Group Anagrams: use a frequency signature or sorted string as dictionary key and bucket words together. Complexity Valid: O(n). Group: O(n…
Short answer: Push opening brackets. On a closing bracket, pop and check it matches. At the end the stack must be empty. Covers (), {}, [] in one pass. Sample solution C# bool IsValid(string s) { var st = new Stack<ch…
Short answer: Iterative: three pointers prev, curr, next. Flip curr.next to prev and advance. Recursive: reverse the rest, then point head.next.next = head and head.next = null. Iterative is usually preferred in intervie…
Short answer: Use a dummy head and append the smaller of the two current nodes until one list is exhausted, then attach the remainder. Recursive merge is elegant but uses stack space. Complexity Time O(n + m), Space O(1)…
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: Climbing Stairs: ways(n) = ways(n-1) + ways(n-2) — Fibonacci DP. House Robber: dp[i] = max(dp[i-1], dp[i-2] + nums[i]) — cannot rob adjacent houses. Both reduce to O(1) space with two rolling variables. Com…
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: Classic DP is O(n²): dp[i] = best LIS ending at i. The optimized patience-sorting / binary-search approach maintains tails of increasing subsequences in O(n log n). Mention both; implement O(n²) unless aske…
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: Hash map from key → node plus a doubly linked list ordered by recency. get/put are O(1): move accessed node to front; on capacity eviction remove from tail. This is one of the most asked system-design-lite…
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: Maintain inclusive or exclusive bounds consistently. Compute mid carefully (lo + (hi − lo) / 2) to avoid overflow. Decide whether you want lower-bound, upper-bound, or exact match before coding. Complexity…
Short answer: Floyd’s tortoise and hare: slow moves 1, fast moves 2. If they meet, there is a cycle. To find the cycle entrance, reset one pointer to head and move both one step until they meet. Complexity Time O(n), Spa…
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: Use preorder with null markers (e.g. "#") or level-order BFS with nulls. Deserialization consumes the same format with a queue/iterator. Clarify the string format with the interviewer first. Complexity Time…
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: Water at i is min(leftMax, rightMax) − height[i]. Compute with two arrays, or optimize with two pointers moving from ends while tracking leftMax/rightMax. Stack-based solution processes bars as histogram va…
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 · Arrays & Hashing
Short answer: Valid Anagram: count character frequencies (or sort both strings). Group Anagrams: use a frequency signature or sorted string as dictionary key and bucket words together.
Valid: O(n). Group: O(n * k log k) with sort key, or O(n * k) with count key (k = word length).
Prefer count[26] for lowercase English — faster and shows constraint awareness.
DSA & Coding Interviews Coding Interview FAQ · Stacks
Short answer: Push opening brackets. On a closing bracket, pop and check it matches. At the end the stack must be empty. Covers (), {}, [] in one pass.
bool IsValid(string s) {
var st = new Stack<char>();
foreach (char c in s) {
if (c is '(' or '[' or '{') st.Push(c);
else {
if (st.Count == 0) return false;
char o = st.Pop();
if ((c == ')' && o != '(') || (c == ']' && o != '[') || (c == '}' && o != '{'))
return false;
}
}
return st.Count == 0;
}
Time O(n), Space O(n).
This is a common phone-screen opener — nail it quickly and cleanly.
DSA & Coding Interviews Coding Interview FAQ · Linked Lists
Short answer: Iterative: three pointers prev, curr, next. Flip curr.next to prev and advance. Recursive: reverse the rest, then point head.next.next = head and head.next = null. Iterative is usually preferred in interviews for O(1) stack space.
Time O(n). Iterative space O(1); recursive space O(n) call stack.
Draw 3 nodes on the whiteboard before coding — it prevents pointer bugs.
DSA & Coding Interviews Coding Interview FAQ · Linked Lists
Short answer: Use a dummy head and append the smaller of the two current nodes until one list is exhausted, then attach the remainder. Recursive merge is elegant but uses stack space.
Time O(n + m), Space O(1) iterative.
Dummy node avoids special-casing the head — a small habit that impresses interviewers.
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: Climbing Stairs: ways(n) = ways(n-1) + ways(n-2) — Fibonacci DP. House Robber: dp[i] = max(dp[i-1], dp[i-2] + nums[i]) — cannot rob adjacent houses. Both reduce to O(1) space with two rolling variables.
Time O(n), Space O(1) optimized.
Always define the recurrence in words before writing code.
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 · Dynamic Programming
Short answer: Classic DP is O(n²): dp[i] = best LIS ending at i. The optimized patience-sorting / binary-search approach maintains tails of increasing subsequences in O(n log n). Mention both; implement O(n²) unless asked for optimal.
DP O(n²); patience sorting O(n log n).
Interviewers love hearing both complexities even if you code the simpler DP.
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 · Design
Short answer: Hash map from key → node plus a doubly linked list ordered by recency. get/put are O(1): move accessed node to front; on capacity eviction remove from tail. This is one of the most asked system-design-lite coding questions.
get/put O(1) average; Space O(capacity).
In C#, LinkedList + Dictionary is the standard interview implementation.
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 · Binary Search
Short answer: Maintain inclusive or exclusive bounds consistently. Compute mid carefully (lo + (hi − lo) / 2) to avoid overflow. Decide whether you want lower-bound, upper-bound, or exact match before coding.
Time O(log n), Space O(1).
State the loop invariant: “answer is always inside [lo, hi]”.
DSA & Coding Interviews Coding Interview FAQ · Linked Lists
Short answer: Floyd’s tortoise and hare: slow moves 1, fast moves 2. If they meet, there is a cycle. To find the cycle entrance, reset one pointer to head and move both one step until they meet.
Time O(n), Space O(1) — better than HashSet of visited nodes.
Mention both HashSet and Floyd; then choose Floyd for O(1) space.
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 · Trees
Short answer: Use preorder with null markers (e.g. "#") or level-order BFS with nulls. Deserialization consumes the same format with a queue/iterator. Clarify the string format with the interviewer first.
Time O(n), Space O(n).
Pick one format and stick to it — inconsistency is a common fail point.
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 · Two Pointers / Stack
Short answer: Water at i is min(leftMax, rightMax) − height[i]. Compute with two arrays, or optimize with two pointers moving from ends while tracking leftMax/rightMax. Stack-based solution processes bars as histogram valleys.
Two pointers O(n) time, O(1) space.
Relate it to Container With Most Water but stress per-index water units.