Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.
C# Coding Interview C# Programming Tutorial · Coding
public int FindKthLargest(int[] nums, int k) {
return QuickSelect(nums, 0, nums.Length - 1, nums.Length - k);
private int QuickSelect(int[] nums, int left, int right, int
kSmallest) {
if (left == right) return nums[left];
int pivotIndex = Partition(nums, left, right);
if (kSmallest == pivotIndex)
return nums[kSmallest];
else if (kSmallest < pivotIndex)
return QuickSelect(nums, left, pivotIndex - 1, kSmallest);
else
return QuickSelect(nums, pivotIndex + 1, right, kSmallest);
private int Partition(int[] nums, int left, int right) {
int pivot = nums[right];
int i = left;
for (int j = left; j < right; j++) {
if (nums[j] <= pivot) {
Swap(nums, i, j);
i++;
Swap(nums, i, right);
return i;
private void Swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
Follow on:
Explanation:
Quickselect partitions the array like Quicksort and recursively searches for the kth smallest
element. Here, nums.Length - k gives the kth largest.
C# Coding Interview C# Programming Tutorial · Coding
public class MyQueue {
private Stack<int> stackIn = new Stack<int>();
private Stack<int> stackOut = new Stack<int>();
// Enqueue: push into stackIn (O(1))
public void Enqueue(int x) {
stackIn.Push(x);
// Dequeue: if stackOut empty, pour all from stackIn to
stackOut, then pop (amortized O(1))
public int Dequeue() {
if (stackOut.Count == 0) {
while (stackIn.Count > 0) {
stackOut.Push(stackIn.Pop());
return stackOut.Pop();
public int Peek() {
if (stackOut.Count == 0) {
while (stackIn.Count > 0) {
stackOut.Push(stackIn.Pop());
return stackOut.Peek();
public bool IsEmpty() {
return stackIn.Count == 0 && stackOut.Count == 0;
Follow on:
Explanation:
Two stacks are used: stackIn for enqueue, stackOut for dequeue. Elements are
transferred only when needed, making both operations amortized O(1).
C# Coding Interview C# Programming Tutorial · Coding
begins
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; next = null; }
ListNode DetectCycle(ListNode head) {
if (head == null) return null;
ListNode slow = head, fast = head;
Follow on:
// Detect cycle using Floyd's Tortoise and Hare
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) { // cycle detected
ListNode ptr = head;
while (ptr != slow) {
ptr = ptr.next;
slow = slow.next;
return ptr; // start node of cycle
return null; // no cycle
Explanation:
First detect cycle meeting point with two pointers. Then find start node by moving one
pointer from head and one from meeting point until they meet.
C# Coding Interview C# Programming Tutorial · Coding
int Fibonacci(int n)
if (n <= 1) return n;
int a = 0, b = 1;
for (int i = 2; i <= n; i++)
int temp = a + b;
a = b;
b = temp;
return b;
Explanation:
Iterative DP approach; each Fibonacci number is sum of two previous.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
substring (needle) in a string (haystack)
int StrStr(string haystack, string needle)
if (needle == "") return 0;
int n = haystack.Length, m = needle.Length;
for (int i = 0; i <= n - m; i++)
int j;
Follow on:
for (j = 0; j < m; j++)
if (haystack[i + j] != needle[j])
break;
if (j == m) return i; // found
return -1;
Explanation:
Simple sliding window check each position; returns starting index or -1.
C# Coding Interview C# Programming Tutorial · Coding
public class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int x) { val = x; }
TreeNode prev = null;
TreeNode head = null;
TreeNode ConvertToDLL(TreeNode root) {
if (root == null) return null;
ConvertToDLL(root.left);
if (prev == null) {
head = root; // first node becomes head
} else {
root.left = prev;
Follow on:
prev.right = root;
prev = root;
ConvertToDLL(root.right);
return head;
Explanation:
Inorder traversal connects nodes as doubly linked list by linking current with previous node.
C# Coding Interview C# Programming Tutorial · Coding
void BFS(Dictionary<int, List<int>> graph, int start) {
var visited = new HashSet<int>();
var queue = new Queue<int>();
queue.Enqueue(start);
visited.Add(start);
while (queue.Count > 0) {
int node = queue.Dequeue();
Console.WriteLine(node);
foreach (var neighbor in graph[node]) {
if (!visited.Contains(neighbor)) {
visited.Add(neighbor);
queue.Enqueue(neighbor);
Explanation:
Classic BFS using a queue and visited set.
C# Coding Interview C# Programming Tutorial · Coding
int MergeSortAndCount(int[] arr, int[] temp, int left, int right)
int invCount = 0;
if (right > left)
int mid = (right + left) / 2;
invCount += MergeSortAndCount(arr, temp, left, mid);
invCount += MergeSortAndCount(arr, temp, mid + 1, right);
invCount += Merge(arr, temp, left, mid + 1, right);
return invCount;
int Merge(int[] arr, int[] temp, int left, int mid, int right)
int i = left, j = mid, k = left;
int invCount = 0;
while (i <= mid - 1 && j <= right)
if (arr[i] <= arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
invCount += (mid - i); // Count inversions
while (i <= mid - 1)
temp[k++] = arr[i++];
Follow on:
while (j <= right)
temp[k++] = arr[j++];
for (int idx = left; idx <= right; idx++)
arr[idx] = temp[idx];
return invCount;
Explanation:
Using a modified merge sort to count pairs where arr[i] > arr[j] for i < j efficiently.
C# Coding Interview C# Programming Tutorial · Coding
int UniquePaths(int m, int n) {
int[,] dp = new int[m, n];
for (int i = 0; i < m; i++) dp[i, 0] = 1;
for (int j = 0; j < n; j++) dp[0, j] = 1;
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i, j] = dp[i - 1, j] + dp[i, j - 1];
return dp[m - 1, n - 1];
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
Algorithm
int GCD(int a, int b)
Follow on:
while (b != 0)
int temp = b;
b = a % b;
a = temp;
return a;
Explanation:
Repeatedly replace (a, b) with (b, a mod b) until b is 0; then a is the GCD.
C# Coding Interview C# Programming Tutorial · Coding
public List<int> PrimeFactors(int n) {
List<int> factors = new List<int>();
// Print the number of 2s that divide n
while (n % 2 == 0) {
factors.Add(2);
n /= 2;
// n must be odd at this point
for (int i = 3; i * i <= n; i += 2) {
while (n % i == 0) {
factors.Add(i);
n /= i;
Follow on:
// If n is a prime number > 2
if (n > 2) {
factors.Add(n);
return factors;
Explanation:
We repeatedly divide by 2, then check odd factors up to √n. If leftover n > 2, it's prime.
C# Coding Interview C# Programming Tutorial · Coding
public List<int> FindAnagrams(string s, string p) {
List<int> result = new List<int>();
if (p.Length > s.Length) return result;
int[] pCount = new int[26];
int[] sCount = new int[26];
Follow on:
for (int i = 0; i < p.Length; i++) {
pCount[p[i] - 'a']++;
sCount[s[i] - 'a']++;
if (Enumerable.SequenceEqual(pCount, sCount))
result.Add(0);
for (int i = p.Length; i < s.Length; i++) {
sCount[s[i] - 'a']++;
sCount[s[i - p.Length] - 'a']--;
if (Enumerable.SequenceEqual(pCount, sCount))
result.Add(i - p.Length + 1);
return result;
Explanation:
Sliding window with frequency count arrays for the pattern and current window.
C# Coding Interview C# Programming Tutorial · Coding
void QuickSort(int[] arr, int low, int high)
if (low < high)
Follow on:
int pi = Partition(arr, low, high);
QuickSort(arr, low, pi - 1);
QuickSort(arr, pi + 1, high);
int Partition(int[] arr, int low, int high)
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++)
if (arr[j] < pivot)
i++;
(arr[i], arr[j]) = (arr[j], arr[i]);
(arr[i + 1], arr[high]) = (arr[high], arr[i + 1]);
return i + 1;
Explanation:
Choose last element as pivot, partition array so left < pivot < right, recursively sort
subarrays.
C# Coding Interview C# Programming Tutorial · Coding
element appears twice
public int SingleNonRepeated(int[] nums) {
int result = 0;
foreach (int num in nums) {
result ^= num;
return result;
Explanation:
XOR of a number with itself is 0; XOR with 0 is the number. So duplicates cancel out,
leaving the unique number.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
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:
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
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:
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
(Repeated here for convenience)
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);
ExpandAroundCenter(s, i, i + 1, ref start, ref maxLen);
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])
Follow on:
if (right - left + 1 > maxLen)
start = left;
maxLen = right - left + 1;
left--;
right++;
C# Coding Interview C# Programming Tutorial · Coding
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;
C# Coding Interview C# Programming Tutorial · Coding
integer
public int CountSetBits(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>= 1;
return count;
Explanation:
Shift through each bit; add 1 to count if least significant bit is set.
Alternative using Brian Kernighan’s algorithm:
public int CountSetBits(int n) {
int count = 0;
while (n != 0) {
n &= (n - 1); // Drops the lowest set bit
count++;
return count;
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
int LCM(int a, int b)
return a / GCD(a, b) * b;
Explanation:
LCM × GCD = product of the two numbers.
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
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).
C# Coding Interview C# Programming Tutorial · Coding
bool IsMatch(string s, string p)
return IsMatchHelper(s, p, 0, 0);
bool IsMatchHelper(string s, string p, int i, int j)
if (j == p.Length) return i == s.Length;
bool firstMatch = (i < s.Length) && (p[j] == s[i] || p[j] ==
'.');
if (j + 1 < p.Length && p[j + 1] == '*')
// Two cases:
// 1) Use zero occurrence of p[j] (skip)
// 2) If firstMatch, consume one char in s and keep pattern
at 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).
C# Coding Interview C# Programming Tutorial · Coding
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).
C# Coding Interview C# Programming Tutorial · Coding
x * half * half : (half * half) / x;
Explanation:
Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n).
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
List<List<int>> Subsets(int[] nums)
List<List<int>> result = new List<List<int>>();
GenerateSubsets(nums, 0, new List<int>(), result);
return result;
void GenerateSubsets(int[] nums, int index, List<int> current,
List<List<int>> result)
if (index == nums.Length)
result.Add(new List<int>(current));
return;
// Exclude nums[index]
GenerateSubsets(nums, index + 1, current, result);
// Include nums[index]
current.Add(nums[index]);
GenerateSubsets(nums, index + 1, current, result);
current.RemoveAt(current.Count - 1);
Follow on:
Explanation:
Backtracking approach includes/excludes each element.
C# Coding Interview C# Programming Tutorial · Coding
int LCS(string s1, string s2)
int m = s1.Length, n = s2.Length;
int[,] dp = new int[m + 1, n + 1];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if (s1[i - 1] == s2[j - 1])
dp[i, j] = dp[i - 1, j - 1] + 1;
else
dp[i, j] = Math.Max(dp[i - 1, j], dp[i, j - 1]);
return dp[m, n];
Explanation:
Build DP table comparing chars; find longest subsequence common to both strings.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
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:
C# Coding Interview C# Programming Tutorial · Coding
bool IsPrime(int n)
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
Follow on:
return true;
Explanation:
Check divisibility by 2, 3, then test possible divisors of form 6k ± 1 up to √n.
C# Coding Interview C# Programming Tutorial · Coding
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;
C# Coding Interview C# Programming Tutorial · Coding
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.
C# Coding Interview C# Programming Tutorial · Coding
int FirstOccurrence(int[] arr, int target)
int low = 0, high = arr.Length - 1, result = -1;
while (low <= high)
int mid = low + (high - low) / 2;
if (arr[mid] == target)
result = mid;
Follow on:
high = mid - 1; // search left side
else if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
return result;
Explanation:
Binary search but continue left to find first occurrence.
C# Coding Interview C# Programming Tutorial · Coding
bool IsIdentical(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
if (p.val != q.val) return false;
return IsIdentical(p.left, q.left) && IsIdentical(p.right,
q.right);
Explanation:
Recursive check values and structure for equality.
C# Coding Interview C# Programming Tutorial · Coding
public bool IsPerfectSquare(int num) {
if (num < 0) return false;
int left = 0, right = num;
while (left <= right) {
int mid = left + (right - left) / 2;
long sq = (long)mid * mid;
if (sq == num) return true;
else if (sq < num) left = mid + 1;
else right = mid - 1;
return false;
Explanation:
Binary search for integer square root and check if square equals num.
C# Coding Interview C# Programming Tutorial · Coding
public int FindMissingNumber(int[] nums, int n) {
int xor = 0;
for (int i = 1; i <= n; i++) {
xor ^= i;
foreach (int num in nums) {
xor ^= num;
return xor;
Follow on:
Explanation:
XOR all numbers from 1 to n and XOR all elements in array; duplicates cancel out, leaving
missing number.
C# Coding Interview C# Programming Tutorial · Coding
public int CountPartitions(int[] nums) {
int sum = 0;
foreach (int num in nums) sum += num;
if (sum % 2 != 0) return 0;
int target = sum / 2;
int[] dp = new int[target + 1];
dp[0] = 1;
Follow on:
foreach (int num in nums) {
for (int j = target; j >= num; j--) {
dp[j] += dp[j - num];
return dp[target];
Explanation:
Classic subset sum DP. dp[j] = ways to get sum j. Counting subsets summing to half the
total.
C# Coding Interview C# Programming Tutorial · Coding
public int MaximumTotal(IList<IList<int>> triangle) {
int n = triangle.Count;
int[] dp = new int[n];
for (int i = 0; i < n; i++) dp[i] = triangle[n - 1][i];
for (int layer = n - 2; layer >= 0; layer--) {
for (int i = 0; i <= layer; i++) {
dp[i] = triangle[layer][i] + Math.Max(dp[i], dp[i + 1]);
return dp[0];
Explanation:
Start from bottom row, keep updating max path sums up to the top.
C# Coding Interview C# Programming Tutorial · Coding
List<List<int>> TarjanSCC(Dictionary<int, List<int>> graph) {
int time = 0;
var stack = new Stack<int>();
var onStack = new HashSet<int>();
var low = new Dictionary<int, int>();
var disc = new Dictionary<int, int>();
var visited = new HashSet<int>();
var sccList = new List<List<int>>();
void DFS(int u) {
disc[u] = time;
Follow on:
low[u] = time;
time++;
stack.Push(u);
onStack.Add(u);
visited.Add(u);
foreach (var v in graph[u]) {
if (!disc.ContainsKey(v)) {
DFS(v);
low[u] = Math.Min(low[u], low[v]);
} else if (onStack.Contains(v)) {
low[u] = Math.Min(low[u], disc[v]);
if (low[u] == disc[u]) {
var scc = new List<int>();
int w;
do {
w = stack.Pop();
onStack.Remove(w);
scc.Add(w);
} while (w != u);
sccList.Add(scc);
foreach (var node in graph.Keys) {
if (!disc.ContainsKey(node))
DFS(node);
return sccList;
Explanation:
Tarjan's algorithm finds SCCs using low-link values and DFS stack.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
int LongestPalindromeSubseq(string s) {
int n = s.Length;
int[,] dp = new int[n, n];
for (int i = n - 1; i >= 0; i--) {
dp[i, i] = 1;
for (int j = i + 1; j < n; j++) {
if (s[i] == s[j])
Follow on:
dp[i, j] = dp[i + 1, j - 1] + 2;
else
dp[i, j] = Math.Max(dp[i + 1, j], dp[i, j - 1]);
return dp[0, n - 1];
C# Coding Interview C# Programming Tutorial · Coding
element in constant time
public class MinStack {
private Stack<int> stack = new Stack<int>();
private Stack<int> minStack = new Stack<int>();
Follow on:
public void Push(int x) {
stack.Push(x);
if (minStack.Count == 0 || x <= minStack.Peek())
minStack.Push(x);
public void Pop() {
if (stack.Peek() == minStack.Peek())
minStack.Pop();
stack.Pop();
public int Top() {
return stack.Peek();
public int GetMin() {
return minStack.Peek();
Explanation:
Use two stacks: one normal stack, one for minimum values. When pushing a smaller or
equal value, push it on minStack; when popping, pop minStack if needed.
C# Coding Interview C# Programming Tutorial · Coding
headB : a.next;
b = (b == null) ? headA : b.next;
return a; // either intersection or null
Explanation:
Two pointers traverse both lists; if no intersection, both will reach null simultaneously.
C# Coding Interview C# Programming Tutorial · Coding
Eratosthenes)
List<int> GeneratePrimes(int n)
bool[] isPrime = new bool[n + 1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i * i <= n; i++)
if (isPrime[i])
for (int j = i * i; j <= n; j += i)
isPrime[j] = false;
List<int> primes = new List<int>();
for (int i = 2; i <= n; i++)
if (isPrime[i]) primes.Add(i);
return primes;
Explanation:
Mark multiples of each prime as non-prime starting from its square.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
String
Dictionary<char, int> CountCharacters(string s)
var dict = new Dictionary<char, int>();
foreach (char c in s)
if (dict.ContainsKey(c))
dict[c]++;
else
dict[c] = 1;
return dict;
Explanation:
Simple frequency map using Dictionary.
C# Coding Interview C# Programming Tutorial · Coding
int LIS(int[] nums)
int n = nums.Length;
int[] dp = new int[n];
Array.Fill(dp, 1);
int maxLen = 1;
for (int i = 1; i < n; i++)
for (int j = 0; j < i; j++)
if (nums[i] > nums[j])
dp[i] = Math.Max(dp[i], dp[j] + 1);
maxLen = Math.Max(maxLen, dp[i]);
return maxLen;
Explanation:
For each element, find LIS ending there by checking previous smaller elements.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
List<List<string>> SolveNQueens(int n)
List<List<string>> results = new List<List<string>>();
int[] board = new int[n]; // board[i] = column position of queen
in row i
Solve(0, board, results, n);
return results;
void Solve(int row, int[] board, List<List<string>> results, int n)
if (row == n)
results.Add(GenerateBoard(board, n));
return;
for (int col = 0; col < n; col++)
if (IsSafe(row, col, board))
board[row] = col;
Solve(row + 1, board, results, n);
bool IsSafe(int row, int col, int[] board)
for (int i = 0; i < row; i++)
Follow on:
if (board[i] == col || Math.Abs(board[i] - col) ==
Math.Abs(i - row))
return false;
return true;
List<string> GenerateBoard(int[] board, int n)
List<string> res = new List<string>();
for (int i = 0; i < n; i++)
char[] row = new char[n];
for (int j = 0; j < n; j++)
row[j] = '.';
row[board[i]] = 'Q';
res.Add(new string(row));
return res;
Explanation:
Backtracking places queens row by row while checking columns and diagonals.
C# Coding Interview C# Programming Tutorial · Coding
int FindPeakElement(int[] nums)
int left = 0, right = nums.Length - 1;
while (left < right)
int mid = (left + right) / 2;
if (nums[mid] > nums[mid + 1])
right = mid;
else
left = mid + 1;
return left;
Explanation:
Binary search comparing mid element with right neighbor to find peak.
C# Coding Interview C# Programming Tutorial · Coding
public int FindCelebrity(int n, Func<int, int, bool> knows) {
int candidate = 0;
for (int i = 1; i < n; i++) {
if (knows(candidate, i)) candidate = i;
for (int i = 0; i < n; i++) {
if (i != candidate && (knows(candidate, i) || !knows(i,
candidate)))
return -1;
return candidate;
Explanation:
First find candidate by elimination, then verify candidate.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
int MinPathSum(int[][] grid) {
int m = grid.Length, n = grid[0].Length;
for (int i = 1; i < m; i++) grid[i][0] += grid[i - 1][0];
for (int j = 1; j < n; j++) grid[0][j] += grid[0][j - 1];
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
grid[i][j] += Math.Min(grid[i - 1][j], grid[i][j - 1]);
return grid[m - 1][n - 1];
C# Coding Interview C# Programming Tutorial · Coding
int SumOfDigits(int n)
int sum = 0;
n = Math.Abs(n);
while (n > 0)
sum += n % 10;
n /= 10;
return sum;
Explanation:
Extract digits using modulo 10 and add.
C# Coding Interview C# Programming Tutorial · Coding
appears twice except one
public int SingleNumber(int[] nums) {
int result = 0;
foreach (var num in nums) {
result ^= num;
return result;
Explanation:
XOR of all elements cancels duplicates, leaving the single unique element.
C# Coding Interview C# Programming Tutorial · Coding
int[] Dijkstra(Dictionary<int, List<(int neighbor, int weight)>>
graph, int source, int vertices) {
int[] dist = new int[vertices];
for (int i = 0; i < vertices; i++) dist[i] = int.MaxValue;
dist[source] = 0;
var pq = new SortedSet<(int dist, int node)>();
pq.Add((0, source));
while (pq.Count > 0) {
var current = pq.Min;
pq.Remove(current);
int u = current.node;
foreach (var (v, w) in graph[u]) {
if (dist[u] + w < dist[v]) {
if (dist[v] != int.MaxValue)
pq.Remove((dist[v], v));
dist[v] = dist[u] + w;
pq.Add((dist[v], v));
return dist;
Explanation:
Uses a priority queue to pick node with min dist; relax edges.
C# Coding Interview C# Programming Tutorial · Coding
Follow on:
int BinarySearch(int[] arr, int target)
int low = 0, high = arr.Length - 1;
while (low <= high)
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
return -1;
Explanation:
Standard binary search to find target’s index or -1 if not found.
C# Coding Interview C# Programming Tutorial · Coding
int NumIslands(char[][] grid)
if (grid == null || grid.Length == 0) return 0;
int count = 0;
for (int i = 0; i < grid.Length; i++)
for (int j = 0; j < grid[0].Length; j++)
if (grid[i][j] == '1')
Follow on:
DFS(grid, i, j);
count++;
return count;
void DFS(char[][] grid, int i, int j)
if (i < 0 || j < 0 || i >= grid.Length || j >= grid[0].Length ||
grid[i][j] == '0')
return;
grid[i][j] = '0'; // Mark visited
DFS(grid, i + 1, j);
DFS(grid, i - 1, j);
DFS(grid, i, j + 1);
DFS(grid, i, j - 1);
Explanation:
Use DFS to mark all connected land cells, count islands by visiting unvisited lands.
C# Coding Interview C# Programming Tutorial · Coding
public int GCD(int a, int b) {
Follow on:
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
return a;
public int LCM(int a, int b) {
return (a / GCD(a, b)) * b;
Explanation:
GCD uses Euclidean algorithm. LCM calculated via LCM(a,b) = (a*b)/GCD(a,b).
C# Coding Interview C# Programming Tutorial · Coding
TreeNode LCA(TreeNode root, int n1, int n2) {
if (root == null) return null;
if (root.val == n1 || root.val == n2) return root;
TreeNode left = LCA(root.left, n1, n2);
Follow on:
TreeNode right = LCA(root.right, n1, n2);
if (left != null && right != null) return root;
return left ?? right;
int FindLevel(TreeNode root, int val, int level) {
if (root == null) return -1;
if (root.val == val) return level;
int left = FindLevel(root.left, val, level + 1);
if (left != -1) return left;
return FindLevel(root.right, val, level + 1);
int DistanceBetweenNodes(TreeNode root, int n1, int n2) {
TreeNode lca = LCA(root, n1, n2);
int d1 = FindLevel(lca, n1, 0);
int d2 = FindLevel(lca, n2, 0);
return d1 + d2;
Explanation:
Find Lowest Common Ancestor (LCA) then sum distances from LCA to each node.
C# Coding Interview C# Programming Tutorial · Coding
Amount)
int CoinChange(int[] coins, int amount)
int[] dp = new int[amount + 1];
Array.Fill(dp, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++)
foreach (int coin in coins)
if (coin <= i)
dp[i] = Math.Min(dp[i], 1 + dp[i - coin]);
return dp[amount] > amount ? -1 : dp[amount];
Explanation:
Bottom-up DP: min coins needed for all amounts up to target.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
public void Swap(ref int a, ref int b) {
if (a != b) {
a ^= b;
b ^= a;
a ^= b;
Explanation:
XOR swap algorithm exchanges values without extra storage. (Check a != b to avoid
zeroing when both are same.)
C# Coding Interview C# Programming Tutorial · Coding
public int[] MaxSlidingWindow(int[] nums, int k) {
if (nums == null || k <= 0) return new int[0];
int n = nums.Length;
int[] result = new int[n - k + 1];
LinkedList<int> deque = new LinkedList<int>(); // store indices
for (int i = 0; i < n; i++) {
// Remove indices out of window
if (deque.Count > 0 && deque.First.Value <= i - k)
Follow on:
deque.RemoveFirst();
// Remove smaller values from the back
while (deque.Count > 0 && nums[deque.Last.Value] < nums[i])
deque.RemoveLast();
deque.AddLast(i);
if (i >= k - 1)
result[i - k + 1] = nums[deque.First.Value];
return result;
Explanation:
Use a deque to keep indexes of useful elements in current window, ensuring the front is
always max.
C# Coding Interview C# Programming Tutorial · Coding
bool IsRotation(string s1, string s2)
if (s1.Length != s2.Length) return false;
string doubled = s1 + s1;
return doubled.Contains(s2);
Follow on:
Explanation:
If s2 is rotation of s1, it must be substring of s1+s1.
C# Coding Interview C# Programming Tutorial · Coding
l1.val : 0;
int y = (l2 != null) ? l2.val : 0;
int sum = x + y + carry;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
Follow on:
return dummy.next;
Explanation:
Add digit by digit with carry, creating new nodes for the result.
C# Coding Interview C# Programming Tutorial · Coding
public class MultiLevelNode {
public int val;
public MultiLevelNode next;
public MultiLevelNode child;
public MultiLevelNode(int x) { val = x; next = null; child =
null; }
MultiLevelNode Flatten(MultiLevelNode head) {
if (head == null) return null;
MultiLevelNode dummy = new MultiLevelNode(0);
MultiLevelNode prev = dummy;
Stack<MultiLevelNode> stack = new Stack<MultiLevelNode>();
stack.Push(head);
while (stack.Count > 0) {
var curr = stack.Pop();
prev.next = curr;
curr.child = null; // remove child pointer after flattening
prev = curr;
if (curr.next != null) stack.Push(curr.next);
if (curr.child != null) stack.Push(curr.child);
return dummy.next;
Follow on:
Explanation:
Use a stack to perform DFS; attach nodes and remove child pointers.
C# Coding Interview C# Programming Tutorial · Coding
public int TrailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
return count;
Explanation:
Count factors of 5 in factorial since 2s are plentiful, trailing zeros depend on 5s.
C# Coding Interview C# Programming Tutorial · Coding
public class TrieNode {
public TrieNode[] Children = new TrieNode[26];
public bool IsEnd = false;
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
public void Insert(string word) {
TrieNode node = root;
foreach (char c in word) {
int idx = c - 'a';
if (node.Children[idx] == null)
node.Children[idx] = new TrieNode();
node = node.Children[idx];
node.IsEnd = true;
public bool Search(string word) {
TrieNode node = SearchNode(word);
return node != null && node.IsEnd;
public bool StartsWith(string prefix) {
return SearchNode(prefix) != null;
private TrieNode SearchNode(string word) {
TrieNode node = root;
foreach (char c in word) {
int idx = c - 'a';
if (node.Children[idx] == null) return null;
Follow on:
node = node.Children[idx];
return node;
Explanation:
Standard trie with insert, search, and prefix checking.
C# Coding Interview C# Programming Tutorial · Coding
bool WordBreak(string s, HashSet<string> wordDict)
bool[] dp = new bool[s.Length + 1];
dp[0] = true;
for (int i = 1; i <= s.Length; i++)
for (int j = 0; j < i; j++)
if (dp[j] && wordDict.Contains(s.Substring(j, i - j)))
dp[i] = true;
break;
return dp[s.Length];
Explanation:
DP to check if substring can be segmented using dictionary words.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
(Others Appear Twice)
int SingleNonDuplicate(int[] nums)
int low = 0, high = nums.Length - 1;
while (low < high)
int mid = low + (high - low) / 2;
if (mid % 2 == 1) mid--; // ensure mid is even
if (nums[mid] == nums[mid + 1])
low = mid + 2;
else
high = mid;
Follow on:
return nums[low];
Explanation:
Pairs appear consecutively; use binary search on even indices to find mismatch.
C# Coding Interview C# Programming Tutorial · Coding
public int[] SearchRange(int[] nums, int target) {
int left = FindBoundary(nums, target, true);
int right = FindBoundary(nums, target, false);
return new int[] { left, right };
private int FindBoundary(int[] nums, int target, bool findFirst) {
Follow on:
int left = 0, right = nums.Length - 1;
int boundary = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
boundary = mid;
if (findFirst)
right = mid - 1;
else
left = mid + 1;
else if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
return boundary;
Explanation:
Binary search twice — once to find first occurrence and once for last occurrence.
C# Coding Interview C# Programming Tutorial · Coding
public uint ReverseBits(uint n) {
uint result = 0;
for (int i = 0; i < 32; i++) {
result <<= 1;
result |= (n & 1);
n >>= 1;
return result;
Explanation:
Iteratively take least significant bit of n, add it to result’s LSB, shift both accordingly.
Follow on:
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
int EditDistance(string word1, string word2) {
int m = word1.Length, n = word2.Length;
int[,] dp = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++) dp[i, 0] = i;
for (int j = 0; j <= n; j++) dp[0, j] = j;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1[i - 1] == word2[j - 1])
dp[i, j] = dp[i - 1, j - 1];
else
Follow on:
dp[i, j] = 1 + Math.Min(dp[i - 1, j - 1],
Math.Min(dp[i - 1, j], dp[i, j - 1]));
return dp[m, n];
C# Coding Interview C# Programming Tutorial · Coding
All Characters of String t
string MinWindow(string s, string t)
if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t)) return
"";
Dictionary<char, int> dictT = new Dictionary<char, int>();
foreach (char c in t)
dictT[c] = dictT.ContainsKey(c) ? dictT[c] + 1 : 1;
int required = dictT.Count;
int formed = 0;
Dictionary<char, int> windowCounts = new Dictionary<char,
int>();
int left = 0, right = 0;
int minLen = int.MaxValue, minLeft = 0;
while (right < s.Length)
char c = s[right];
windowCounts[c] = windowCounts.ContainsKey(c) ?
windowCounts[c] + 1 : 1;
if (dictT.ContainsKey(c) && windowCounts[c] == dictT[c])
formed++;
while (left <= right && formed == required)
if (right - left + 1 < minLen)
minLen = right - left + 1;
Follow on:
minLeft = left;
char leftChar = s[left];
windowCounts[leftChar]--;
if (dictT.ContainsKey(leftChar) &&
windowCounts[leftChar] < dictT[leftChar])
formed--;
left++;
right++;
return minLen == int.MaxValue ? "" : s.Substring(minLeft,
minLen);
Explanation:
Sliding window with two pointers keeps track of counts of chars matching the target.
C# Coding Interview C# Programming Tutorial · Coding
int TrailingZeroes(int n)
int count = 0;
for (int i = 5; i <= n; i *= 5)
count += n / i;
return count;
Explanation:
Trailing zeros come from factors of 10 = 2 × 5, but 2s are plenty, count 5s.
C# Coding Interview C# Programming Tutorial · Coding
List<List<int>> LevelOrderBottom(TreeNode root) {
var res = new List<List<int>>();
if (root == null) return res;
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0) {
int size = queue.Count;
var level = new List<int>();
Follow on:
for (int i = 0; i < size; i++) {
TreeNode node = queue.Dequeue();
level.Add(node.val);
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
res.Insert(0, level); // prepend to get reverse order
return res;
Explanation:
Perform normal BFS, insert each level at front of result list for reversed order.
C# Coding Interview C# Programming Tutorial · Coding
Array
int LongestConsecutive(int[] nums)
HashSet<int> set = new HashSet<int>(nums);
int longest = 0;
foreach (int num in set)
if (!set.Contains(num - 1))
Follow on:
int currentNum = num;
int length = 1;
while (set.Contains(currentNum + 1))
currentNum++;
length++;
longest = Math.Max(longest, length);
return longest;
Explanation:
Check only starts of sequences, count consecutive numbers using HashSet for O(n).
C# Coding Interview C# Programming Tutorial · Coding
void PrintNodesAtLevel(Dictionary<int, List<int>> graph, int start,
int targetLevel) {
var visited = new HashSet<int>();
var queue = new Queue<(int node, int level)>();
Follow on:
queue.Enqueue((start, 0));
visited.Add(start);
while (queue.Count > 0) {
var (node, level) = queue.Dequeue();
if (level == targetLevel) {
Console.WriteLine(node);
if (level > targetLevel) break;
foreach (var neighbor in graph[node]) {
if (!visited.Contains(neighbor)) {
visited.Add(neighbor);
queue.Enqueue((neighbor, level + 1));
Explanation:
BFS traversal with level tracking; print nodes at the requested level.
C# Coding Interview C# Programming Tutorial · Coding
int MinCutPalindromePartition(string s) {
int n = s.Length;
bool[,] dp = new bool[n, n];
int[] cuts = new int[n];
for (int i = 0; i < n; i++) {
int minCuts = i;
for (int j = 0; j <= i; j++) {
if (s[j] == s[i] && (i - j < 2 || dp[j + 1, i - 1])) {
dp[j, i] = true;
minCuts = j == 0 ? 0 : Math.Min(minCuts, cuts[j - 1]
+ 1);
cuts[i] = minCuts;
return cuts[n - 1];
C# Coding Interview C# Programming Tutorial · Coding
1 : -1;
return candidate;
Explanation:
Boyer-Moore Voting Algorithm tracks majority element by counting net votes.
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
int MaxSubArray(int[] nums)
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (int i = 1; i < nums.Length; i++)
maxEndingHere = Math.Max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.Max(maxSoFar, maxEndingHere);
return maxSoFar;
Explanation:
Track max subarray ending at current position; update global max.
C# Coding Interview C# Programming Tutorial · Coding
public int FindDuplicate(int[] nums) {
int slow = nums[0], fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
fast = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
return slow;
Explanation:
Floyd’s Tortoise and Hare cycle detection, treating values as pointers.
C# Coding Interview C# Programming Tutorial · Coding
bool PrintAncestors(TreeNode root, int target) {
if (root == null) return false;
if (root.val == target) return true;
if (PrintAncestors(root.left, target) ||
PrintAncestors(root.right, target)) {
Console.Write(root.val + " ");
return true;
return false;
Explanation:
Recursive check if target is in subtree; print current node on path back if yes.
C# Coding Interview C# Programming Tutorial · Coding
1 : -1;
return candidate;
Explanation:
Maintain a candidate and count; majority element survives this cancellation.
C# Coding Interview C# Programming Tutorial · Coding
x * temp * temp : (temp * temp) / x;
Explanation:
Recursive fast power divides exponent by 2 to reduce complexity to O(log n).
C# Coding Interview C# Programming Tutorial · Coding
int KthSmallest(int[][] matrix, int k)
int n = matrix.Length;
int low = matrix[0][0], high = matrix[n - 1][n - 1];
while (low < high)
Follow on:
int mid = low + (high - low) / 2;
int count = 0, j = n - 1;
for (int i = 0; i < n; i++)
while (j >= 0 && matrix[i][j] > mid)
j--;
count += (j + 1);
if (count < k)
low = mid + 1;
else
high = mid;
return low;
Explanation:
Binary search on values, count how many elements ≤ mid using matrix’s sorted rows/cols.
C# Coding Interview C# Programming Tutorial · Coding
int MaxSumIncreasingSubsequence(int[] nums) {
int n = nums.Length;
int[] dp = new int[n];
Array.Copy(nums, dp, n);
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
Follow on:
if (nums[i] > nums[j])
dp[i] = Math.Max(dp[i], dp[j] + nums[i]);
return dp.Max();
C# Coding Interview C# Programming Tutorial · Coding
void RotateMatrix(int[][] matrix)
int n = matrix.Length;
// Transpose
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
(matrix[i][j], matrix[j][i]) = (matrix[j][i],
matrix[i][j]);
// Reverse each row
for (int i = 0; i < n; i++)
int left = 0, right = n - 1;
while (left < right)
(matrix[i][left], matrix[i][right]) = (matrix[i][right],
matrix[i][left]);
left++;
right--;
Explanation:
Transpose matrix and then reverse each row to rotate clockwise by 90°.
C# Coding Interview C# Programming Tutorial · Coding
public int LengthOfLongestSubstringTwoDistinct(string s) {
int left = 0, right = 0, maxLen = 0;
Dictionary<char, int> map = new Dictionary<char, int>();
while (right < s.Length) {
Follow on:
char c = s[right];
map[c] = right;
if (map.Count > 2) {
int delIndex = map.Values.Min();
map.Remove(s[delIndex]);
left = delIndex + 1;
maxLen = Math.Max(maxLen, right - left + 1);
right++;
return maxLen;
Explanation:
Sliding window with hashmap to track indices of distinct chars, remove the leftmost when
>2.
C# Coding Interview C# Programming Tutorial · Coding
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 removes one set bit per iteration.
C# Coding Interview C# Programming Tutorial · Coding
int RodCutting(int[] prices, int n)
int[] dp = new int[n + 1];
dp[0] = 0;
Follow on:
for (int i = 1; i <= n; i++)
int maxVal = int.MinValue;
for (int j = 0; j < i; j++)
maxVal = Math.Max(maxVal, prices[j] + dp[i - j - 1]);
dp[i] = maxVal;
return dp[n];
Explanation:
Max revenue by cutting rod into pieces of various lengths.
C# Coding Interview C# Programming Tutorial · Coding
min, int? max) {
if (node == null) return true;
if ((min != null && node.val <= min) || (max != null && node.val
>= max)) return false;
return Validate(node.left, min, node.val) &&
Validate(node.right, node.val, max);
Explanation:
Pass down min and max bounds for subtree values; node must be in (min, max) range.
C# Coding Interview C# Programming Tutorial · Coding
int MatrixChainOrder(int[] dims)
int n = dims.Length - 1;
int[,] dp = new int[n, n];
for (int l = 2; l <= n; l++)
Follow on:
for (int i = 0; i < n - l + 1; i++)
int j = i + l - 1;
dp[i, j] = int.MaxValue;
for (int k = i; k < j; k++)
int cost = dp[i, k] + dp[k + 1, j] + dims[i] *
dims[k + 1] * dims[j + 1];
dp[i, j] = Math.Min(dp[i, j], cost);
return dp[0, n - 1];
Explanation:
DP calculates minimal cost to multiply chain of matrices by trying all partitions.
C# Coding Interview C# Programming Tutorial · Coding
void SortColors(int[] nums)
int low = 0, mid = 0, high = nums.Length - 1;
while (mid <= high)
if (nums[mid] == 0)
(nums[low++], nums[mid++]) = (nums[mid], nums[low]);
else if (nums[mid] == 1)
mid++;
else
(nums[mid], nums[high--]) = (nums[high], nums[mid]);
Follow on:
Explanation:
Partition array into three parts in one pass using three pointers.
C# Coding Interview C# Programming Tutorial · Coding
public bool IsBalanced(string s) {
Stack<char> stack = new Stack<char>();
Dictionary<char, char> pairs = new Dictionary<char, char> {
{')', '('}, {']', '['}, {'}', '{'}
foreach (char c in s) {
if ("([{".Contains(c))
stack.Push(c);
else if (")]}".Contains(c)) {
if (stack.Count == 0 || stack.Pop() != pairs[c])
return false;
return stack.Count == 0;
Follow on:
Explanation:
Use a stack to match opening and closing brackets properly.
C# Coding Interview C# Programming Tutorial · Coding
int WidthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
int maxWidth = 0;
Queue<(TreeNode node, int idx)> queue = new Queue<(TreeNode,
int)>();
queue.Enqueue((root, 0));
while (queue.Count > 0) {
int size = queue.Count;
int start = queue.Peek().idx;
int end = start;
for (int i = 0; i < size; i++) {
var (node, idx) = queue.Dequeue();
end = idx;
if (node.left != null)
queue.Enqueue((node.left, 2 * idx + 1));
if (node.right != null)
queue.Enqueue((node.right, 2 * idx + 2));
maxWidth = Math.Max(maxWidth, end - start + 1);
Follow on:
return maxWidth;
Explanation:
Assign index to each node as if in a complete tree; width is max difference of indices per
level.
C# Coding Interview C# Programming Tutorial · Coding
List<string> WordBreak(string s, IList<string> wordDict) {
var wordSet = new HashSet<string>(wordDict);
var memo = new Dictionary<int, List<string>>();
return DFS(0);
List<string> DFS(int start) {
if (memo.ContainsKey(start)) return memo[start];
var res = new List<string>();
if (start == s.Length) {
res.Add("");
return res;
for (int end = start + 1; end <= s.Length; end++) {
string word = s.Substring(start, end - start);
if (wordSet.Contains(word)) {
foreach (var sub in DFS(end)) {
string space = sub.Length == 0 ? "" : " ";
res.Add(word + space + sub);
memo[start] = res;
return res;
Follow on:
C# Coding Interview C# Programming Tutorial · Coding
a / b : throw new DivideByZeroException(),
_ => throw new ArgumentException("Invalid operator"),
Explanation:
Simple switch statement performing basic arithmetic, with divide-by-zero check.
C# Coding Interview C# Programming Tutorial · Coding
bool SolveSudoku(char[][] board)
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
Follow on:
if (board[i][j] == '.')
for (char c = '1'; c <= '9'; c++)
if (IsValid(board, i, j, c))
board[i][j] = c;
if (SolveSudoku(board))
return true;
else
board[i][j] = '.';
return false;
return true;
bool IsValid(char[][] board, int row, int col, char c)
for (int i = 0; i < 9; i++)
if (board[row][i] == c) return false;
if (board[i][col] == c) return false;
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] ==
c) return false;
return true;
Explanation:
Backtracking tries digits 1-9 in empty cells, validating constraints.
C# Coding Interview C# Programming Tutorial · Coding
bool CanPartition(int[] nums)
int sum = nums.Sum();
Follow on:
if (sum % 2 != 0) return false;
int target = sum / 2;
bool[] dp = new bool[target + 1];
dp[0] = true;
foreach (int num in nums)
for (int j = target; j >= num; j--)
dp[j] = dp[j] || dp[j - num];
return dp[target];
Explanation:
Subset sum to check if half the total sum is achievable.
Sorting and Searching
C# Coding Interview C# Programming Tutorial · Coding
Integers
int FindMissingNumber(int[] nums)
int low = 0, high = nums.Length - 1;
while (low <= high)
int mid = low + (high - low) / 2;
if (nums[mid] == mid)
low = mid + 1;
else
high = mid - 1;
return low;
Explanation:
In perfect array nums[i] == i; missing number breaks this property, use binary search to find
breakpoint.
Mathematical Problems
C# Coding Interview C# Programming Tutorial · Coding
public void RotateMatrix(int[][] matrix) {
int n = matrix.Length;
// Transpose
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
// Reverse each row
for (int i = 0; i < n; i++) {
Array.Reverse(matrix[i]);
Explanation:
Transpose matrix and then reverse each row to rotate 90° clockwise.
C# Coding Interview C# Programming Tutorial · Coding
Follow on:
List<string> GenerateParenthesis(int n)
List<string> result = new List<string>();
Generate("", 0, 0, n, result);
return result;
void Generate(string current, int open, int close, int max,
List<string> result)
if (current.Length == max * 2)
result.Add(current);
return;
if (open < max)
Generate(current + "(", open + 1, close, max, result);
if (close < open)
Generate(current + ")", open, close + 1, max, result);
Explanation:
Use backtracking to add '(' and ')' only when valid.
C# Coding Interview C# Programming Tutorial · Coding
long LargestPrimeFactor(long n)
long maxPrime = -1;
while (n % 2 == 0)
maxPrime = 2;
n /= 2;
for (long i = 3; i * i <= n; i += 2)
while (n % i == 0)
maxPrime = i;
n /= i;
if (n > 2) maxPrime = n;
return maxPrime;
Follow on:
Explanation:
Divide out factors of 2, then test odd factors; leftover > 2 is prime.
Miscellaneous Problems