Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
Short answer: rray.Copy(arr, left, L, 0, n1); rray.Copy(arr, mid + 1, R, 0, n2); int i = 0, j = 0, k = left; while (i < n1 && j < n2) rr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++]; while (i < n1) arr[k++…
Short answer: public int CountOnes(int n) { int count = 0; while (n != 0) { n &= (n - 1); // Drops the lowest set bit count++; } return count; } Explanation: Brian Kernighan’s algorithm efficiently removes the lowest…
Short answer: public string LongestCommonPrefix(string[] strs) { if (strs == null || strs.Length == 0) return ""; for (int i = 0; i < strs[0].Length; i++) { char c = strs[0][i]; for (int j = 1; j < strs.L…
Short answer: public int[] SortNearlySorted(int[] nums, int k) { var result = new List<int>(); var minHeap = new SortedSet<(int val, int index)>(); for (int i = 0; i < nums.Length; i++) { minHeap.Add((nums…
Short answer: int ClimbStairs(int n) { if (n <= 2) return n; int a = 1, b = 2; for (int i = 3; i <= n; i++) { int c = a + b; a = b; b = c; } return b; } Example code int ClimbStairs(int n) { if (n <= 2) return n…
Short answer: int CountConnectedComponents(Dictionary<int, List<int>> graph) { var visited = new HashSet<int>(); int count = 0; Follow on: foreach (var node in graph.Keys) { if (!visited.Contains(node))…
Short answer: void VerticalSum(TreeNode root, int hd, Dictionary<int, int> map) { if (root == null) return; VerticalSum(root.left, hd - 1, map); if (map.ContainsKey(hd)) map[hd] += root.val; else map[hd] = root.val…
Short answer: public int EvaluateInfix(string expression) { Stack<int> operands = new Stack<int>(); Stack<char> operators = new Stack<char>(); int i = 0; while (i < expression.Length) { if (cha…
Short answer: ListNode ReverseBetween(ListNode head, int m, int n) { Example code if (head == null || m == n) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode prev = dummy; // Move prev to one b…
Short answer: string LongestPalindrome(string s) { if (string.IsNullOrEmpty(s)) return ""; int start = 0, maxLen = 1; for (int i = 0; i < s.Length; i++) { ExpandAroundCenter(s, i, i, ref start, ref maxLen);…
Short answer: int LCM(int a, int b) { return a / GCD(a, b) * b; } Explanation: LCM × GCD = product of the two numbers. Example code int LCM(int a, int b) { return a / GCD(a, b) * b; } Explanation: LCM × GCD = product of…
Short answer: void MergeSort(int[] arr, int left, int right) { Example code if (left < right) { int mid = (left + right) / 2; MergeSort(arr, left, mid); MergeSort(arr, mid + 1, right); Follow on: Merge(arr, left, mid,…
Short answer: int Knapsack(int[] weights, int[] values, int W) { int n = weights.Length; int[,] dp = new int[n + 1, W + 1]; for (int i = 1; i <= n; i++) { for (int w = 1; w <= W; w++) { if (weights[i - 1] <= w)…
Short answer: Logic Convert to char array. Swap characters from both ends. string str = "dotnet"; char[] chars = str.ToCharArray(); int left = 0, right = chars.Length - 1; while (left < right) { char temp =…
Short answer: public double Power(double x, int n) { if (n == 0) return 1; double half = Power(x, n / 2); if (n % 2 == 0) return half * half; else return n > 0 ? x * half * half : (half * half) / x; } Explanation: Use…
Short answer: t j return IsMatchHelper(s, p, i, j + 2) || (firstMatch && IsMatchHelper(s, p, i + 1, j)); } else { return firstMatch && IsMatchHelper(s, p, i + 1, j + 1); } Follow on: } Explanation: Recurs…
Short answer: public bool HaveOppositeSigns(int x, int y) { return (x ^ y) < 0; } Explanation: XOR of two numbers with opposite signs has the sign bit set (negative number). Example code public bool HaveOppositeSigns(…
Short answer: public class NestedIterator { private Queue<int> queue; public NestedIterator(IList<NestedInteger> nestedList) { queue = new Queue<int>(); Flatten(nestedList); } private void Flatten(IList…
Short answer: x * half * half : (half * half) / x; Explanation: Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n). Explain a bit more x * half * half : (half * half) / x; Explanation: Uses fast e…
Short answer: public class MedianFinder { private PriorityQueue<int, int> maxHeap; // lower half (max heap) Follow on: private PriorityQueue<int, int> minHeap; // upper half (min heap) public MedianFinder() {…
Short answer: int HouseRobber(int[] nums) { if (nums.Length == 0) return 0; if (nums.Length == 1) return nums[0]; int prev1 = 0, prev2 = 0; foreach (var num in nums) { int temp = prev1; prev1 = Math.Max(prev2 + num, prev…
Short answer: public class Edge { public int Source, Dest, Weight; public Edge(int s, int d, int w) { Source = s; Dest = d; Weight = w; } } int[] BellmanFord(int vertices, List<Edge> edges, int source) { int[] dist…
Short answer: TreeNode prev = null; void Flatten(TreeNode root) { if (root == null) return; Flatten(root.right); Flatten(root.left); root.right = prev; root.left = null; prev = root; } Explanation: Postorder traversal (r…
Short answer: int[] NextGreaterElements(int[] nums) { int n = nums.Length; int[] result = new int[n]; Stack<int> stack = new Stack<int>(); for (int i = n - 1; i >= 0; i--) { while (stack.Count > 0 &…
Short answer: ListNode MergeKLists(ListNode[] lists) { Example code if (lists == null || lists.Length == 0) return null; PriorityQueue<ListNode, int> pq = new PriorityQueue<ListNode, int>(); foreach (var list…
C# Coding Interview C# Programming Tutorial · Coding
Short answer: rray.Copy(arr, left, L, 0, n1); rray.Copy(arr, mid + 1, R, 0, n2); int i = 0, j = 0, k = left; while (i < n1 && j < n2) rr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++]; while (i < n1) arr[k++] = L[i++]; while (j < n2) arr[k++] = R[j++]; } Explanation: Divide array, sort left & right halves, then merge sorted halves. while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
} Explanation: Divide array, sort left & right halves, then merge sorted halves.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: public int CountOnes(int n) { int count = 0; while (n != 0) { n &= (n - 1); // Drops the lowest set bit count++; } return count; } Explanation: Brian Kernighan’s algorithm efficiently removes the lowest set bit each iteration until zero.
public int CountOnes(int n) {
int count = 0; while (n != 0) { n &= (n - 1); // Drops the lowest set bit count++; }
return count;
} Explanation: Brian Kernighan’s algorithm efficiently removes the lowest set bit each iteration until zero.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: public string LongestCommonPrefix(string[] strs) { if (strs == null || strs.Length == 0) return ""; for (int i = 0; i < strs[0].Length; i++) { char c = strs[0][i]; for (int j = 1; j < strs.Length; j++) { if (i == strs[j].Length || strs[j][i] != c) return strs[0].Substring(0, i); } } return strs[0]; } Follow on: Explanation: Check character by character across all strings until mismatch.
public string LongestCommonPrefix(string[] strs) {
if (strs == null || strs.Length == 0) return "";
for (int i = 0; i < strs[0].Length; i++) {
char c = strs[0][i];
for (int j = 1; j < strs.Length; j++) {
if (i == strs[j].Length || strs[j][i] != c)
return strs[0].Substring(0, i);
}
}
return strs[0];
} Follow on: Explanation: Check character by character across all strings until mismatch.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: public int[] SortNearlySorted(int[] nums, int k) { var result = new List<int>(); var minHeap = new SortedSet<(int val, int index)>(); for (int i = 0; i < nums.Length; i++) { minHeap.Add((nums[i], i)); if (minHeap.Count > k) { var min = minHeap.Min; minHeap.Remove(min); result.Add(min.val); } } while (minHeap.Count > 0) { var min = minHeap.Min; minHeap.Remove(min); result.Add(min.val); } return result.ToArray(); }…
Explanation: Use a min-heap of size k+1 to always extract the smallest element in the current window.
public int[] SortNearlySorted(int[] nums, int k) {
var result = new List<int>();
var minHeap = new SortedSet<(int val, int index)>();
for (int i = 0; i < nums.Length; i++) { minHeap.Add((nums[i], i)); if (minHeap.Count > k) {
var min = minHeap.Min; minHeap.Remove(min); result.Add(min.val); }
} while (minHeap.Count > 0) { var min = minHeap.Min; minHeap.Remove(min); result.Add(min.val); }
return result.ToArray();
} Explanation: Use a min-heap of size k+1 to always extract the smallest element in the current window.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: int ClimbStairs(int n) { if (n <= 2) return n; int a = 1, b = 2; for (int i = 3; i <= n; i++) { int c = a + b; a = b; b = c; } return b; }
int ClimbStairs(int n) {
if (n <= 2) return n;
int a = 1, b = 2;
for (int i = 3; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: int CountConnectedComponents(Dictionary<int, List<int>> graph) { var visited = new HashSet<int>(); int count = 0; Follow on: foreach (var node in graph.Keys) { if (!visited.Contains(node)) { DFS(node, graph, visited); count++; } } return count; } void DFS(int node, Dictionary<int, List<int>> graph, HashSet<int> visited) { visited.Add(node); foreach (var neighbor in graph[node]) { if (!visited.Contains(neighbor)) {…
DFS(neighbor, graph, visited); } } } Explanation: Run DFS on unvisited nodes, count how many times DFS starts.
int CountConnectedComponents(Dictionary<int, List<int>> graph) {
var visited = new HashSet<int>();
int count = 0; Follow on: foreach (var node in graph.Keys) {
if (!visited.Contains(node)) { DFS(node, graph, visited); count++; }
}
return count;
} void DFS(int node, Dictionary<int, List<int>> graph, HashSet<int> visited) { visited.Add(node); foreach (var neighbor in graph[node]) {
if (!visited.Contains(neighbor)) { DFS(neighbor, graph, visited); }
}
} Explanation: Run DFS on unvisited nodes, count how many times DFS starts.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: void VerticalSum(TreeNode root, int hd, Dictionary<int, int> map) { if (root == null) return; VerticalSum(root.left, hd - 1, map); if (map.ContainsKey(hd)) map[hd] += root.val; else map[hd] = root.val; VerticalSum(root.right, hd + 1, map); } Dictionary<int, int> GetVerticalSum(TreeNode root) { var map = new Dictionary<int, int>(); VerticalSum(root, 0, map); return map; } Explanation: Use horizontal distance (hd)…
from root; sum values of nodes at each hd. Follow on:
void VerticalSum(TreeNode root, int hd, Dictionary<int, int> map) { if (root == null) return; VerticalSum(root.left, hd - 1, map); if (map.ContainsKey(hd))
map[hd] += root.val; else map[hd] = root.val; VerticalSum(root.right, hd + 1, map); }
Dictionary<int, int> GetVerticalSum(TreeNode root) {
var map = new Dictionary<int, int>(); VerticalSum(root, 0, map); return map;
} Explanation: Use horizontal distance (hd) from root; sum values of nodes at each hd. Follow on:
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: public int EvaluateInfix(string expression) { Stack<int> operands = new Stack<int>(); Stack<char> operators = new Stack<char>(); int i = 0; while (i < expression.Length) { if (char.IsWhiteSpace(expression[i])) { i++; continue; } if (char.IsDigit(expression[i])) { int val = 0; while (i < expression.Length && char.IsDigit(expression[i])) { val = val * 10 + (expression[i] - '0'); i++; } operands.Push(val); continue; }…
if (expression[i] == '(') { operators.Push(expression[i]); } else if (expression[i] == ')') { while (operators.Peek() != '(') { ApplyOp(operands, operators); } operators.Pop(); // remove '(' Follow on: } else if (IsOperator(expression[i])) { while (operators.Count > 0 && Precedence(operators.Peek()) >= Precedence(expression[i])) { ApplyOp(operands, operators); } operators.Push(expression[i]); } i++; } while (operators.Count > 0) { ApplyOp(operands, operators); } return operands.Pop(); } bool IsOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } int Precedence(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; return 0; } void ApplyOp(Stack<int> operands, Stack<char> operators) { int b = operands.Pop(); int a = operands.Pop(); char op = operators.Pop(); int result = 0; switch (op) { case '+': result = a + b; break; case '-':…
public int EvaluateInfix(string expression) {
Stack<int> operands = new Stack<int>();
Stack<char> operators = new Stack<char>();
int i = 0; while (i < expression.Length) { if (char.IsWhiteSpace(expression[i])) { i++; continue; }
if (char.IsDigit(expression[i])) {
int val = 0; while (i < expression.Length && char.IsDigit(expression[i])) { val = val * 10 + (expression[i] - '0'); i++; } operands.Push(val); continue; }
if (expression[i] == '(') { operators.Push(expression[i]); } else if (expression[i] == ')') { while (operators.Peek() != '(') { ApplyOp(operands, operators); } operators.Pop(); // remove '(' Follow on: } else if (IsOperator(expression[i])) { while (operators.Count > 0 && Precedence(operators.Peek()) >= Precedence(expression[i])) { ApplyOp(operands, operators); } operators.Push(expression[i]); } i++; } while (operators.Count > 0) { ApplyOp(operands, operators); }
return operands.Pop();
} bool IsOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/';
}
int Precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
} void ApplyOp(Stack<int> operands, Stack<char> operators) { int b = operands.Pop();
int a = operands.Pop();
char op = operators.Pop();
int result = 0; switch (op) { case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break; Follow on: case '/': result = a / b; break;
} operands.Push(result); } Explanation: Standard two-stack algorithm for evaluating infix expressions considering operator precedence and parentheses.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: ListNode ReverseBetween(ListNode head, int m, int n) {
if (head == null || m == n) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy; // Move prev to one before m-th node for (int i = 1; i < m; i++) prev = prev.next;
ListNode start = prev.next;
ListNode then = start.next; // Reverse the sublist for (int i = 0; i < n - m; i++) { Follow on: start.next = then.next;
then.next = prev.next;
prev.next = then;
then = start.next;
}
return dummy.next;
} Explanation: Use a dummy node to simplify edge cases. Reverse nodes between m and n by changing pointers.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: string LongestPalindrome(string s) { if (string.IsNullOrEmpty(s)) return ""; int start = 0, maxLen = 1; for (int i = 0; i < s.Length; i++) { ExpandAroundCenter(s, i, i, ref start, ref maxLen); // Odd length palindrome ExpandAroundCenter(s, i, i + 1, ref start, ref maxLen); // Even length palindrome } return s.Substring(start, maxLen); } void ExpandAroundCenter(string s, int left, int right, ref int start, ref int…
maxLen) { while (left >= 0 && right < s.Length && s[left] == s[right]) { if (right - left + 1 > maxLen) Follow on: { start = left; maxLen = right - left + 1; } left--; right++; } } Explanation: Expand around each center to find the longest palindrome in O(n²).
string LongestPalindrome(string s)
{
if (string.IsNullOrEmpty(s)) return "";
int start = 0, maxLen = 1;
for (int i = 0; i < s.Length; i++)
{ ExpandAroundCenter(s, i, i, ref start, ref maxLen); // Odd length palindrome ExpandAroundCenter(s, i, i + 1, ref start, ref maxLen); // Even length palindrome }
return s.Substring(start, maxLen);
} void ExpandAroundCenter(string s, int left, int right, ref int start, ref int maxLen) { while (left >= 0 && right < s.Length && s[left] == s[right]) {
if (right - left + 1 > maxLen) Follow on: {
start = left;
maxLen = right - left + 1;
} left--; right++; }
} Explanation: Expand around each center to find the longest palindrome in O(n²).
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: int LCM(int a, int b) { return a / GCD(a, b) * b; } Explanation: LCM × GCD = product of the two numbers.
int LCM(int a, int b)
{
return a / GCD(a, b) * b;
} Explanation: LCM × GCD = product of the two numbers.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: void MergeSort(int[] arr, int left, int right) {
if (left < right)
{
int mid = (left + right) / 2; MergeSort(arr, left, mid); MergeSort(arr, mid + 1, right); Follow on: Merge(arr, left, mid, right); }
} void Merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] L = new int[n1];
int[] R = new int[n2]; Array.Copy(arr, left, L, 0, n1); Array.Copy(arr, mid + 1, R, 0, n2); int i = 0, j = 0, k = left; while (i < n1 && j < n2) arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
} Explanation: Divide array, sort left & right halves, then merge sorted halves.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: int Knapsack(int[] weights, int[] values, int W) { int n = weights.Length; int[,] dp = new int[n + 1, W + 1]; for (int i = 1; i <= n; i++) { for (int w = 1; w <= W; w++) { if (weights[i - 1] <= w) dp[i, w] = Math.Max(dp[i - 1, w], values[i - 1] + dp[i - 1, w - weights[i - 1]]); else dp[i, w] = dp[i - 1, w]; } } return dp[n, W]; } Explanation: Build table where dp[i,w] = max value using first i items and capacity w.
int Knapsack(int[] weights, int[] values, int W)
{
int n = weights.Length;
int[,] dp = new int[n + 1, W + 1];
for (int i = 1; i <= n; i++)
{
for (int w = 1; w <= W; w++)
{
if (weights[i - 1] <= w) dp[i, w] = Math.Max(dp[i - 1, w], values[i - 1] + dp[i - 1, w - weights[i - 1]]); else dp[i, w] = dp[i - 1, w];
}
}
return dp[n, W];
} Explanation: Build table where dp[i,w] = max value using first i items and capacity w. Follow on:
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding Scenarios
Short answer: Logic Convert to char array. Swap characters from both ends. string str = "dotnet"; char[] chars = str.ToCharArray(); int left = 0, right = chars.Length - 1; while (left < right) { char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } string reversed = new string(chars);
Logic Convert to char array. Swap characters from both ends. string str = "dotnet";
char[] chars = str.ToCharArray();
int left = 0, right = chars.Length - 1; while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp; left++; right--; }
string reversed = new string(chars);
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: public double Power(double x, int n) { if (n == 0) return 1; double half = Power(x, n / 2); if (n % 2 == 0) return half * half; else return n > 0 ? x * half * half : (half * half) / x; } Explanation: Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n).
public double Power(double x, int n) {
if (n == 0) return 1;
double half = Power(x, n / 2);
if (n % 2 == 0)
return half * half; else return n > 0 ? x * half * half : (half * half) / x;
} Explanation: Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n).
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: t j return IsMatchHelper(s, p, i, j + 2) || (firstMatch && IsMatchHelper(s, p, i + 1, j)); } else { return firstMatch && IsMatchHelper(s, p, i + 1, j + 1); } Follow on: } Explanation: Recursively matches strings supporting '.' (any char) and '*' (zero or more of preceding).
t j return IsMatchHelper(s, p, i, j + 2) || (firstMatch && IsMatchHelper(s, p, i + 1, j)); } else { return firstMatch && IsMatchHelper(s, p, i + 1, j + 1); } Follow on: } Explanation: Recursively matches strings supporting '.' (any char) and '*' (zero or more of preceding). t j return IsMatchHelper(s, p, i, j + 2) || (firstMatch && IsMatchHelper(s, p, i + 1, j)); } else { return firstMatch && IsMatchHelper(s, p, i + 1, j + 1); } Follow on: } Explanation: Recursively matches strings supporting '.' (any char) and '*' (zero or more of preceding).
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: public bool HaveOppositeSigns(int x, int y) { return (x ^ y) < 0; } Explanation: XOR of two numbers with opposite signs has the sign bit set (negative number).
public bool HaveOppositeSigns(int x, int y) {
return (x ^ y) < 0;
} Explanation: XOR of two numbers with opposite signs has the sign bit set (negative number).
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: public class NestedIterator { private Queue<int> queue; public NestedIterator(IList<NestedInteger> nestedList) { queue = new Queue<int>(); Flatten(nestedList); } private void Flatten(IList<NestedInteger> nestedList) { foreach (var ni in nestedList) { if (ni.IsInteger()) queue.Enqueue(ni.GetInteger()); else Flatten(ni.GetList()); } } public bool HasNext() { return queue.Count > 0; } public int Next() { return…
queue.Dequeue(); } } Note: NestedInteger is an interface with methods: IsInteger(), GetInteger(), GetList(). Explanation: Pre-flatten the nested list into a queue and iterate over it. Follow on:
public class NestedIterator {
private Queue<int> queue;
public NestedIterator(IList<NestedInteger> nestedList) {
queue = new Queue<int>(); Flatten(nestedList); }
private void Flatten(IList<NestedInteger> nestedList) {
foreach (var ni in nestedList) {
if (ni.IsInteger()) queue.Enqueue(ni.GetInteger()); else Flatten(ni.GetList()); }
}
public bool HasNext() {
return queue.Count > 0;
}
public int Next() {
return queue.Dequeue();
}
} Note: NestedInteger is an interface with methods: IsInteger(), GetInteger(), GetList(). Explanation: Pre-flatten the nested list into a queue and iterate over it. Follow on:
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: x * half * half : (half * half) / x; Explanation: Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n).
x * half * half : (half * half) / x; Explanation: Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n). x * half * half : (half * half) / x; Explanation: Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n). x * half * half : (half * half) / x; Explanation: Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n).
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: public class MedianFinder { private PriorityQueue<int, int> maxHeap; // lower half (max heap) Follow on: private PriorityQueue<int, int> minHeap; // upper half (min heap) public MedianFinder() { maxHeap = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b.CompareTo(a))); minHeap = new PriorityQueue<int, int>(); } public void AddNum(int num) { maxHeap.Enqueue(num, num); minHeap.Enqueue(maxHeap.Dequeue(),…
maxHeap.Peek()); if (maxHeap.Count < minHeap.Count) maxHeap.Enqueue(minHeap.Dequeue(), minHeap.Peek()); } public double FindMedian() { if (maxHeap.Count > minHeap.Count) return maxHeap.Peek(); return (maxHeap.Peek() + minHeap.Peek()) / 2.0; } } Explanation: Maintain two heaps: maxHeap for lower half, minHeap for upper half. Balance their sizes.
public class MedianFinder {
private PriorityQueue<int, int> maxHeap; // lower half (max heap) Follow on: private PriorityQueue<int, int> minHeap; // upper half (min heap) public MedianFinder() { maxHeap = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));
minHeap = new PriorityQueue<int, int>();
}
public void AddNum(int num) { maxHeap.Enqueue(num, num); minHeap.Enqueue(maxHeap.Dequeue(), maxHeap.Peek()); if (maxHeap.Count < minHeap.Count) maxHeap.Enqueue(minHeap.Dequeue(), minHeap.Peek()); }
public double FindMedian() {
if (maxHeap.Count > minHeap.Count)
return maxHeap.Peek();
return (maxHeap.Peek() + minHeap.Peek()) / 2.0;
}
} Explanation: Maintain two heaps: maxHeap for lower half, minHeap for upper half. Balance their sizes.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: int HouseRobber(int[] nums) { if (nums.Length == 0) return 0; if (nums.Length == 1) return nums[0]; int prev1 = 0, prev2 = 0; foreach (var num in nums) { int temp = prev1; prev1 = Math.Max(prev2 + num, prev1); prev2 = temp; } return prev1; }
int HouseRobber(int[] nums) {
if (nums.Length == 0) return 0;
if (nums.Length == 1) return nums[0];
int prev1 = 0, prev2 = 0;
foreach (var num in nums) {
int temp = prev1;
prev1 = Math.Max(prev2 + num, prev1);
prev2 = temp;
}
return prev1;
}
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: public class Edge { public int Source, Dest, Weight; public Edge(int s, int d, int w) { Source = s; Dest = d; Weight = w; } } int[] BellmanFord(int vertices, List<Edge> edges, int source) { int[] dist = new int[vertices]; for (int i = 0; i < vertices; i++) dist[i] = int.MaxValue; dist[source] = 0; Follow on: for (int i = 1; i < vertices; i++) { foreach (var edge in edges) { if (dist[edge.Source] != int.MaxValue &&…
dist[edge.Source] + edge.Weight < dist[edge.Dest]) { dist[edge.Dest] = dist[edge.Source] + edge.Weight; } } } // Detect negative weight cycle (optional) foreach (var edge in edges) { if (dist[edge.Source] != int.MaxValue && dist[edge.Source] + edge.Weight < dist[edge.Dest]) { throw new Exception("Graph contains negative weight cycle"); } } return dist; } Explanation: Relax edges V-1 times, then check for negative weight cycles.
public class Edge {
public int Source, Dest, Weight;
public Edge(int s, int d, int w) {
Source = s; Dest = d; Weight = w;
}
}
int[] BellmanFord(int vertices, List<Edge> edges, int source) {
int[] dist = new int[vertices];
for (int i = 0; i < vertices; i++) dist[i] = int.MaxValue;
dist[source] = 0; Follow on: for (int i = 1; i < vertices; i++) {
foreach (var edge in edges) {
if (dist[edge.Source] != int.MaxValue && dist[edge.Source] + edge.Weight < dist[edge.Dest]) { dist[edge.Dest] = dist[edge.Source] + edge.Weight;
}
}
} // Detect negative weight cycle (optional) foreach (var edge in edges) {
if (dist[edge.Source] != int.MaxValue && dist[edge.Source] + edge.Weight < dist[edge.Dest]) { throw new Exception("Graph contains negative weight cycle"); }
}
return dist;
} Explanation: Relax edges V-1 times, then check for negative weight cycles.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: TreeNode prev = null; void Flatten(TreeNode root) { if (root == null) return; Flatten(root.right); Flatten(root.left); root.right = prev; root.left = null; prev = root; } Explanation: Postorder traversal (right-left-root) to flatten tree in place.
TreeNode prev = null; void Flatten(TreeNode root) { if (root == null) return; Flatten(root.right); Flatten(root.left); root.right = prev;
root.left = null;
prev = root;
} Explanation: Postorder traversal (right-left-root) to flatten tree in place.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: int[] NextGreaterElements(int[] nums) { int n = nums.Length; int[] result = new int[n]; Stack<int> stack = new Stack<int>(); for (int i = n - 1; i >= 0; i--) { while (stack.Count > 0 && stack.Peek() <= nums[i]) { stack.Pop(); } result[i] = stack.Count == 0 ? -1 : stack.Peek(); stack.Push(nums[i]); } return result; } Explanation: Traverse from right to left, use stack to keep track of next greater elements in O(n).
int[] NextGreaterElements(int[] nums) {
int n = nums.Length;
int[] result = new int[n];
Stack<int> stack = new Stack<int>();
for (int i = n - 1; i >= 0; i--) { while (stack.Count > 0 && stack.Peek() <= nums[i]) { stack.Pop(); }
result[i] = stack.Count == 0 ? -1 : stack.Peek(); stack.Push(nums[i]); }
return result;
} Explanation: Traverse from right to left, use stack to keep track of next greater elements in O(n).
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
C# Coding Interview C# Programming Tutorial · Coding
Short answer: ListNode MergeKLists(ListNode[] lists) {
if (lists == null || lists.Length == 0) return null; PriorityQueue<ListNode, int> pq = new PriorityQueue<ListNode, int>();
foreach (var list in lists)
if (list != null) pq.Enqueue(list, list.val); ListNode dummy = new ListNode(0);
ListNode current = dummy; while (pq.Count > 0) { var node = pq.Dequeue();
current.next = node;
current = current.next;
if (node.next != null) pq.Enqueue(node.next, node.next.val); }
return dummy.next;
} Follow on: Explanation: Use a min-heap (priority queue) to always pick the smallest head node among k lists.
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).