Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
Short answer: Use a hash map from value → index while scanning once. For each number x, check if target − x is already seen; if yes, return both indices. This is O(n) time and O(n) space — the expected answer after you b…
Short answer: Track the minimum price so far while scanning left to right. At each day, compute profit = price − minSoFar and keep the maximum profit. One pass, O(1) extra space. Problem statement prices[i] is the stock…
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: Insert elements into a HashSet while scanning. If an insert fails (already present), return true. Sorting and comparing neighbors also works in O(n log n) with O(1) extra space if sorting in place is allowe…
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: 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: 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-…
DSA & Coding Interviews Coding Interview FAQ · Arrays & Hashing
Short answer: Use a hash map from value → index while scanning once. For each number x, check if target − x is already seen; if yes, return both indices. This is O(n) time and O(n) space — the expected answer after you briefly mention the O(n²) nested-loop brute force.
Given an array of integers and a target, return indices of two numbers that add up to the target. Assume exactly one solution and you may not use the same element twice.
Nested loops comparing every pair — correct but too slow for large n.
One pass with Dictionary/HashMap. Lookup is average O(1).
// C#
int[] TwoSum(int[] nums, int target) {
var map = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++) {
int need = target - nums[i];
if (map.TryGetValue(need, out int j)) return new[] { j, i };
map[nums[i]] = i;
}
throw new InvalidOperationException("No solution");
}
Time O(n), Space O(n).
Always start with brute force, then optimize — interviewers score communication as much as code.
DSA & Coding Interviews Coding Interview FAQ · Arrays & Greedy
Short answer: Track the minimum price so far while scanning left to right. At each day, compute profit = price − minSoFar and keep the maximum profit. One pass, O(1) extra space.
prices[i] is the stock price on day i. You may buy once and sell once later. Return the maximum profit (0 if no profit).
int MaxProfit(int[] prices) {
int minPrice = int.MaxValue, best = 0;
foreach (int p in prices) {
if (p < minPrice) minPrice = p;
else best = Math.Max(best, p - minPrice);
}
return best;
}
Time O(n), Space O(1).
Say “running minimum” out loud — it shows you understand the greedy invariant.
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 & Hashing
Short answer: Insert elements into a HashSet while scanning. If an insert fails (already present), return true. Sorting and comparing neighbors also works in O(n log n) with O(1) extra space if sorting in place is allowed.
bool ContainsDuplicate(int[] nums) {
var seen = new HashSet<int>();
foreach (int n in nums)
if (!seen.Add(n)) return true;
return false;
}
HashSet: Time O(n), Space O(n). Sort: Time O(n log n), Space O(1)/O(n).
Ask whether O(1) space matters — that steers you to sorting vs hashing.
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 · 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 · 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.