Technical interview Q&A plus 100+ career & HR questions—notice period, salary negotiation, resume, LinkedIn, freelancing, AI careers, and behavioral interviews with detailed, real-world answers.
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
Answer: 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:
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
Answer: lgorithm int GCD(int a, int b) { Follow on: while (b != 0) { int temp = b; b = a % b; = temp; } return a; } Explanation: Repeatedly replace (a, b) with (b, a mod b) until b is 0; then a is the GCD.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
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
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
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
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
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 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
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
Answer: = b; b = temp; } return b; } Explanation: Iterative DP approach; each Fibonacci number is sum of two previous. Follow on:
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding Scenarios
LINQ Distinct())
Logic
int[] arr = { 1, 2, 3, 2, 4, 1 };
HashSet<int> set = new HashSet<int>();
List<int> result = new List<int>();
foreach (int num in arr)
{
if (!set.Contains(num))
{
set.Add(num);
result.Add(num);
}
}
Why this works:
HashSet ensures uniqueness with O(1) lookup.
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
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
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;
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding
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.
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
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
Answer: lternative 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:
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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 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
Answer: int LCM(int a, int b) { return a / GCD(a, b) * b; } Explanation: LCM × GCD = product of the two numbers.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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 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 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
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
Answer: x * half * half : (half * half) / x; Explanation: Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n).
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding
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).
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
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 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
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
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
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
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 Scenarios
Logic
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);C# Coding Interview C# Programming Tutorial · Coding
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).
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
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
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).
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 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
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
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
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
Answer: 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.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
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
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
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
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
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
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 Scenarios
Logic
bool IsAnagram(string s1, string s2)
{
if (s1.Length != s2.Length) return false;
int[] count = new int[256];
foreach (char c in s1) count[c]++;
foreach (char c in s2) count[c]--;
foreach (int i in count)
if (i != 0) return false;
return true;
}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
rray.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
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
Answer: = (a == null) ? 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.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
Answer: = 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).
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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[] 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
mount)
int CoinChange(int[] coins, int amount)
{
int[] dp = new int[amount + 1];
rray.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
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
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
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
Answer: ^= b; b ^= a; ^= b; } } Explanation: XOR swap algorithm exchanges values without extra storage. (Check a != b to avoid zeroing when both are same.)
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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 Scenarios
Logic
int[] arr = { 10, 5, 20, 8 };
int first = int.MinValue, second = int.MinValue;
foreach (int num in arr)
{
if (num > first)
{
second = first;
first = num;
}
else if (num > second && num != first)
{
second = num;
}
}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
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
Answer: ppears 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.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding
Answer: 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.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding
Answer: 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.)
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding
Answer: 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.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
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
Answer: 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.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
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
rray
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
ll 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
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
Answer: 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.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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 Scenarios
string sentence = "dotnet is great dotnet is powerful";
string[] words = sentence.Split(' ');
Dictionary<string, int> map = new Dictionary<string, int>();
foreach (string word in words)
map[word] = map.ContainsKey(word) ? map[word] + 1 : 1;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
(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
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
lgorithm)
int MajorityElement(int[] nums)
{
int count = 0, candidate = 0;
foreach (var num in nums)
{
if (count == 0)
candidate = num;
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
Explanation:
Maintain a candidate and count; majority element survives this cancellation.
C# Coding Interview C# Programming Tutorial · Coding
Answer: 1 : -1; return candidate; Explanation: Boyer-Moore Voting Algorithm tracks majority element by counting net votes. Follow on:
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding
int MajorityElement(int[] nums)
{
int count = 0, candidate = 0;
foreach (var num in nums)
{
if (count == 0)
candidate = num;
count += (num == candidate) ? 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
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 Scenarios
string input = "programming";
Dictionary<char, int> map = new Dictionary<char, int>();
foreach (char c in input)
map[c] = map.ContainsKey(c) ? map[c] + 1 : 1;
foreach (var item in map)
{
if (item.Value > 1)
Console.WriteLine(item.Key);
}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
double Power(double x, int n)
Follow on:
{
if (n == 0) return 1;
double temp = Power(x, n / 2);
if (n % 2 == 0)
return temp * temp;
else
return (n > 0) ? 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 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
Answer: x * temp * temp : (temp * temp) / x; Explanation: Recursive fast power divides exponent by 2 to reduce complexity to O(log n).
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding
Answer: 1 : -1; return candidate; Explanation: Maintain a candidate and count; majority element survives this cancellation.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
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
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
Answer: 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.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
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 Scenarios
public sealed class Singleton
{
private static readonly object lockObj = new object();
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (lockObj)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}C# Coding Interview C# Programming Tutorial · Coding
Answer: rray.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(); }
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding
bool IsValidBST(TreeNode root) {
return Validate(root, null, null);
}
Follow on:
bool Validate(TreeNode node, int? 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 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
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
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
Answer: a / b : throw new DivideByZeroException(), _ => throw new ArgumentException("Invalid operator"), Explanation: Simple switch statement performing basic arithmetic, with divide-by-zero check.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
double Calculate(double a, double b, char op)
{
return op switch
{
'+' => a + b,
Follow on:
'-' => a - b,
'*' => a * b,
'/' => b != 0 ? 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 Scenarios
ctualSum += num; int missing = expectedSum - actualSum;
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
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
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
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
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
C# Coding Interview C# Programming Tutorial · Coding Scenarios
rray.Reverse(words); string result = string.Join(" ", words);
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
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
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
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
Answer: rray.Reverse(matrix[i]); } } Explanation: Transpose matrix and then reverse each row to rotate 90° clockwise.
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding Scenarios
Answer: bool IsPalindrome(string str) { int left = 0, right = str.Length - 1; while (left < right) { if (str[left] != str[right]) return false; left++; right--; } return true; }
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding Scenarios
Answer: int[] arr = { 3, 5, 1, 5, 2 }; HashSet<int> set = new HashSet<int>(); foreach (int num in arr) { if (!set.Add(num)) { Console.WriteLine(num); break; } }
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding Scenarios
int[] a = { 1, 3, 5 };
int[] b = { 2, 4, 6 };
int i = 0, j = 0;
List<int> result = new List<int>();
while (i < a.Length && j < b.Length)
result.Add(a[i] < b[j] ? a[i++] : b[j++]);
while (i < a.Length) result.Add(a[i++]);
while (j < b.Length) result.Add(b[j++]);
C# Coding Interview C# Programming Tutorial · Coding Scenarios
Answer: string sentence = "CSharp makes backend development powerful"; string[] words = sentence.Split(' '); string longest = words[0]; foreach (string word in words) { if (word.Length > longest.Length) longest = word; }
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding Scenarios
List<object> list = new List<object> { 1, new List<int> { 2, 3 }, 4
};
List<int> result = new List<int>();
void Flatten(List<object> input)
{
foreach (var item in input)
{
if (item is int)
result.Add((int)item);
else
Flatten((List<object>)item);
}
}C# Coding Interview C# Programming Tutorial · Coding Scenarios
rr[j] = arr[j + 1]; rr[j + 1] = temp; } } }
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding Scenarios
Answer: string input = "DotNet"; Dictionary<char, int> map = new Dictionary<char, int>(); foreach (char c in input.ToLower()) map[c] = map.ContainsKey(c) ? map[c] + 1 : 1;
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding Scenarios
Answer: bool IsSorted(int[] arr) { for (int i = 0; i < arr.Length - 1; i++) { if (arr[i] > arr[i + 1]) return false; } return true; }
In a production C# Coding Interview application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Coding Interview C# Programming Tutorial · Coding Scenarios
string input = "Dot@Net#2024!";
StringBuilder sb = new StringBuilder();
foreach (char c in input)
{
if (char.IsLetterOrDigit(c))
sb.Append(c);
}
string result = sb.ToString();
Final Notes
C# Collections C# Programming Tutorial · Collections
LinkedList<T> is a doubly linked list collection in C#. It stores elements as nodes,
where each node contains the data and references to the previous and next nodes.
Example:
LinkedList<int> numbers = new LinkedList<int>();
numbers.AddLast(10);
numbers.AddLast(20);
C# Collections C# Programming Tutorial · Collections
A Queue<T> is a generic collection in C# that stores elements in a First-In, First-Out
(FIFO) order.
Use case:
Modeling real-world queues — e.g., print jobs, task scheduling, or customer service
systems.
Example:
Queue<string> orders = new Queue<string>();
orders.Enqueue("Order1");
orders.Enqueue("Order2");
C# Collections C# Programming Tutorial · Collections
LinkedList<T> is a doubly linked list collection in C#. It stores elements as nodes,
where each node contains the data and references to the previous and next nodes.
Example:
LinkedList<int> numbers = new LinkedList<int>();
numbers.AddLast(10);
numbers.AddLast(20);
C# Collections C# Programming Tutorial · Collections
A Dictionary<TKey, TValue> is a generic collection in C# that stores data as
key-value pairs. It provides fast lookup, addition, and removal of values based on their
keys.
Example:
Dictionary<string, int> ages = new Dictionary<string, int>();
ges.Add("Alice", 30);
ges.Add("Bob", 25);
Use case: Storing user profiles by ID, or mapping product names to prices.
C# Collections C# Programming Tutorial · Collections
Generic collections are type-safe and defined using generics (<T>), allowing you to specify
the type of elements they hold. This ensures compile-time type checking and eliminates the
need for casting.
Non-generic collections, on the other hand, store elements as objects (object type),
requiring boxing/unboxing for value types and casting for reference types.
Example:
// Generic collection
List<int> numbers = new List<int>();
numbers.Add(10); // No boxing, type-safe
// Non-generic collection
rrayList list = new ArrayList();
list.Add(10); // Boxing occurs
int value = (int)list[0]; // Needs casting
Real-world use case:
In applications dealing with specific data types (e.g., a list of customer IDs), generic
collections are ideal. Non-generic collections may be used in legacy systems or when
dealing with multiple data types.
C# Collections C# Programming Tutorial · Collections
List<T> is a generic collection in C# that represents a dynamically sized list of elements.
It resides in the System.Collections.Generic namespace and grows or shrinks as
needed.
Use it when:
Example:
List<string> names = new List<string>();
names.Add("Alice");
C# Collections C# Programming Tutorial · Collections
HashSet<T> is a generic collection that stores unique elements with no particular order.
It is optimized for fast lookups, additions, and deletions.
Use case:
When you want to store a collection of unique items without duplicates, such as user IDs,
tags, or keywords.
HashSet<int> uniqueNumbers = new HashSet<int> { 1, 2, 3 };
uniqueNumbers.Add(4);
C# Collections C# Programming Tutorial · Collections
Answer: List<string> fruits = new List<string> { "Apple", "Banana" }; foreach (var fruit in fruits) { Console.WriteLine(fruit); }
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
A Stack<T> is a generic collection in C# that stores elements in a Last-In, First-Out
(LIFO) order.
Real-world use case:
Undo operations, browser history, expression evaluation.
Example:
Stack<int> numbers = new Stack<int>();
numbers.Push(10);
numbers.Push(20); // Top of the stack
C# Collections C# Programming Tutorial · Collections
SortedList<TKey, TValue> is a collection of key-value pairs that maintains the
elements sorted by keys.
IList<KeyValuePair<TKey, TValue>>.
or a provided comparer.
Example:
SortedList<int, string> sortedList = new SortedList<int, string>();
sortedList.Add(3, "Three");
sortedList.Add(1, "One");
sortedList.Add(2, "Two");
The elements are stored sorted by key: 1, 2, 3.
C# Collections C# Programming Tutorial · Collections
To implement a custom collection:
interfaces such as ICollection<T>, IEnumerable<T>, or IList<T>.
GetEnumerator(), and indexers.
Example:
public class MyCustomCollection<T> : Collection<T>
{
protected override void InsertItem(int index, T item)
{
// Custom validation
if (item == null) throw new
rgumentNullException(nameof(item));
base.InsertItem(index, item);
}
}C# Collections C# Programming Tutorial · Collections
SortedSet<T> is a collection that stores unique elements in sorted order.
Example:
SortedSet<int> sortedSet = new SortedSet<int> { 5, 1, 3 };
sortedSet.Add(2); // Sorted order maintained: {1, 2, 3, 5}
C# Collections C# Programming Tutorial · Collections
Collection initializers allow you to create and populate a collection in a concise way at the
time of declaration.
Example:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 }
};
This syntax internally calls the collection’s Add() method for each element.
C# Collections C# Programming Tutorial · Collections
ccurately.
deeper insights.
multiple times and averaging results.
Example:
var stopwatch = Stopwatch.StartNew();
list.Add(1000);
stopwatch.Stop();
Console.WriteLine($"Add operation took {stopwatch.ElapsedTicks}
ticks");
C# Collections C# Programming Tutorial · Collections
ConcurrentDictionary<TKey, TValue> is a thread-safe dictionary designed for
concurrent access by multiple threads without needing external synchronization (locks).
Example:
ConcurrentDictionary<int, string> concurrentDict = new
ConcurrentDictionary<int, string>();
concurrentDict.TryAdd(1, "One");
concurrentDict.TryUpdate(1, "Uno", "One");
C# Collections C# Programming Tutorial · Collections
clear, allowing easy customization.
extensibility.
validation, event firing).
C# Collections C# Programming Tutorial · Collections
cache-friendly.
Previous), leading to more memory overhead.
performance than LinkedList<T>, especially for large collections.
C# Collections C# Programming Tutorial · Collections
Feature ConcurrentQueue<T> Queue<T>
Thread safety Designed for concurrent access Not thread-safe; requires locks
Locking
mechanism
Internal lock-free or fine-grained
locking
No internal synchronization
Suitable for Multi-threaded
producer-consumer patterns
Single-threaded scenarios or
external synchronization
ConcurrentQueue<T> allows safe enqueueing and dequeueing by multiple threads
simultaneously without corrupting the data.
C# Collections C# Programming Tutorial · Collections
LINQ itself doesn’t modify collections directly but produces new collections based on
queries.
You typically combine LINQ with collection methods to add elements, for example:
var evenNumbers = new List<int> { 2, 4, 6 };
var allNumbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var combined = allNumbers.Where(n => n % 2 == 0).ToList(); //
Filters even numbers
If you want to add LINQ results to a collection:
List<int> filteredNumbers = allNumbers.Where(n => n % 2 ==
0).ToList();
C# Collections C# Programming Tutorial · Collections
Feature SortedSet<T> HashSet<T>
Ordering Maintains sorted order No guaranteed order
Implementation Balanced binary search tree Hash table
Lookup
complexity
O(log n) O(1) average
Memory
overhead
Higher (tree nodes) Lower (hash buckets)
Use case When sorted data or range
queries needed
Fast insertion and lookup without
ordering
C# Collections C# Programming Tutorial · Collections
Generic collections offer several advantages:
Example:
List<string> names = new List<string>();
names.Add("Alice"); // Valid
// names.Add(123); // Compile-time error
Real-world use case:
When managing a list of product names or order numbers, using List<string> or
List<int> ensures that invalid data types are caught at compile time.C# Collections C# Programming Tutorial · Collections
Internally, Queue<T> uses a circular array to efficiently manage memory and operations.
This implementation ensures constant time operations for enqueue and dequeue.
C# Collections C# Programming Tutorial · Collections
Answer: You can use the Add() or AddRange() method. Example: List<int> numbers = new List<int>(); numbers.Add(10); // Add single item numbers.AddRange(new int[] { 20, 30 }); // Add multiple
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Feature SortedList<TKey, TValue> Dictionary<TKey, TValue>
Order Maintains keys in sorted order No guaranteed order
Internal storage Uses two arrays (keys &
values)
Uses a hash table
Lookup complexity O(log n) (binary search) O(1) average
Insertion complexity O(n) (due to shifting elements) O(1) average
Memory overhead Lower (arrays) Higher (hash buckets,
overhead)
C# Collections C# Programming Tutorial · Collections
Answer: Use AddFirst(value) to add at the start. Use AddLast(value) to add at the end. numbers.AddFirst(5); // Adds 5 at the beginning numbers.AddLast(30); // Adds 30 at the end
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Add() method or the indexer []: // Using Add() dictionary.Add("key1", "value1"); // Using indexer dictionary["key2"] = "value2"; Note: Add() throws an exception if the key already exists, while indexer will overwrite the value.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Feature HashSet<T> List<T> Dictionary<TKey,
TValue>
llows
duplicates?
No Yes Keys: No; Values: Yes
Order No guaranteed
order
Maintains insertion
order
No guaranteed order
Lookup speed O(1) average O(n) O(1) average for keys
Key-value pairs No (only values) No Yes (key-value pairs)
C# Collections C# Programming Tutorial · Collections
Internally, Queue<T> uses a circular array to efficiently manage memory and operations.
This implementation ensures constant time operations for enqueue and dequeue.
C# Collections C# Programming Tutorial · Collections
for (int i = 0; i < fruits.Count; i++) { Console.WriteLine(fruits[i]); }
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Internally, Stack<T> uses an array-based dynamic storage system:
doubles)
This structure provides fast push and pop operations (constant time on average).
C# Collections C# Programming Tutorial · Collections
Scenario Best Choice Trade-offs
Fast indexed
ccess
List<T> Slower inserts/removes in
the middle
Frequent
insert/delete at
ends
LinkedList<T> No fast indexed access;
higher memory use
Fast lookups by
key
Dictionary<TKey, TValue> No sorted order
Sorted key-value
pairs
SortedList<TKey, TValue> or
SortedDictionary<TKey,
TValue>
Slower inserts vs
Dictionary
Thread-safe
multi-thread use
ConcurrentDictionary /
ConcurrentQueue
Slight overhead for
synchronization
C# Collections C# Programming Tutorial · Collections
Use methods like:
Example:
numbers.Remove(10);
numbers.RemoveAt(0);
numbers.RemoveAll(x => x > 100);
numbers.Clear();
C# Collections C# Programming Tutorial · Collections
Answer: Use the Remove(key) method: dictionary.Remove("key1"); Returns true if the key was found and removed, false otherwise.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Operation Method Description
dd Enqueue
()
dds an item to the end of the queue
Remove Dequeue
()
Removes and returns the item at the front
Peek Peek() Returns the front item without removing it
Example:
Queue<int> queue = new Queue<int>();
queue.Enqueue(1); // Add
int front = queue.Dequeue(); // RemoveC# Collections C# Programming Tutorial · Collections
C# Collections C# Programming Tutorial · Collections
Example:
var products = new List<Product> { ... };
// Filter products with price > 100
var expensiveProducts = products.Where(p => p.Price > 100);
// Sort products by name
var sortedProducts = products.OrderBy(p => p.Name);
// Group products by category
var groupedProducts = products.GroupBy(p => p.Category);C# Collections C# Programming Tutorial · Collections
ConcurrentQueue, BlockingCollection, etc.).
ReaderWriterLock around critical sections when using non-thread-safe
collections.
C# Collections C# Programming Tutorial · Collections
IEnumerable<T> is the base interface for all generic collections that can be enumerated
(looped over). It allows the use of foreach loops and LINQ queries.
It defines a single method:
IEnumerator<T> GetEnumerator();
Example:
List<string> items = new List<string> { "A", "B", "C" };
foreach (string item in items) // IEnumerable<string> in action
{
Console.WriteLine(item);
}
Real-world use case:
When reading product data from a list or querying a database, IEnumerable<T> allows
deferred execution and efficient data processing using LINQ.
C# Collections C# Programming Tutorial · Collections
Method Description
Push() Adds an element to the top
Pop() Removes and returns the top element
Peek() Returns top element without removing it
Clear(
Removes all elements
Example:
stack.Push(100); // Add
int top = stack.Pop(); // Remove and return topC# Collections C# Programming Tutorial · Collections
(used in sorting operations like Sort()).
GetHashCode(T obj) to determine equality and hashing (used in dictionaries,
sets, etc.).
beyond default implementations.
C# Collections C# Programming Tutorial · Collections
Answer: All these operations generally have O(1) average time complexity due to the underlying hash table structure.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Use Remove(value) to remove the first occurrence of the specified value, or
RemoveFirst() / RemoveLast() to remove from the start or end respectively.
numbers.Remove(10); // Removes the first node with value 10
numbers.RemoveFirst(); // Removes the first node
numbers.RemoveLast(); // Removes the last node
C# Collections C# Programming Tutorial · Collections
Answer: dd: sortedList.Add(4, "Four"); Remove: sortedList.Remove(2); // Remove element with key 2 Search (by key): bool exists = sortedList.ContainsKey(3); string value = sortedList[3]; // Access value by key
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Operation Method Description
Union UnionWith() Adds all elements from another set
Intersection IntersectWit
h()
Keeps only elements present in both
sets
Difference ExceptWith() Removes elements found in another set
Example:
SortedSet<int> set1 = new SortedSet<int> { 1, 2, 3 };
SortedSet<int> set2 = new SortedSet<int> { 3, 4, 5 };
set1.UnionWith(set2); // {1, 2, 3, 4, 5}
set1.IntersectWith(set2); // {3, 4, 5} (if applied on the original
set1)
set1.ExceptWith(set2); // {1, 2} (if applied on the original
set1)
C# Collections C# Programming Tutorial · Collections
Feature BlockingCollection<T> Collection<T>
Thread safety Thread-safe for adding and taking items Not thread-safe
Blocking
behavior
Supports blocking and bounding (waits when
empty/full)
No blocking behavior
Use case Producer-consumer scenarios General-purpose
collection
dditional
features
Supports bounded capacity and cancellation Basic collection
BlockingCollection<T> wraps around other thread-safe collections and provides
blocking and bounding capabilities, ideal for producer-consumer queues.
📘 C# Collections: Performance &
Memory Considerations – Interview Q&A
C# Collections C# Programming Tutorial · Collections
Answer: Enqueue() → O(1) average case Dequeue() → O(1) average case Due to the internal circular array and pointer arithmetic, both operations are highly efficient unless resizing is needed (which is O(n), but infrequent).
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Example (manual):
List<MyClass> DeepClone(List<MyClass> original)
{
return original.Select(item => item.Clone()).ToList();
}
Note: MyClass must implement a Clone() method that performs deep copy.
C# Collections C# Programming Tutorial · Collections
Searching by key uses binary search, so the time complexity is O(log n).
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Add all elements from the collection to a HashSet<T>, which automatically removes
duplicates.
List<int> numbers = new List<int> { 1, 2, 2, 3, 3, 4 };
HashSet<int> uniqueNumbers = new HashSet<int>(numbers);
Now, uniqueNumbers contains only unique values: {1, 2, 3, 4}.
C# Collections C# Programming Tutorial · Collections
Answer: Push() → O(1) average, O(n) worst-case (if resizing needed) Pop() → O(1) These operations are fast and efficient due to the internal array structure.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
List<T>(capacity)) to avoid frequent resizing.
LinkedList<T> if indexing is needed).
non-generic.
📘 C# Advanced Collection Topics –
Interview Questions & AnswersC# Collections C# Programming Tutorial · Collections
Answer: Accessing an element by index is O(1) (constant time) — same as arrays. Example: int first = numbers[0]; // O(1)
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: ContainsKey(key) – checks for key existence ContainsValue(value) – checks for value Example: dictionary.ContainsKey("Alice"); // true/false dictionary.ContainsValue(30); // true/false
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use a foreach loop to traverse the linked list from start to end. foreach (var num in numbers) { Console.WriteLine(num); }
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
expressive.
performance.
C# Collections C# Programming Tutorial · Collections
ICollection<T> extends IEnumerable<T> and adds features like:
Difference:
Example:
ICollection<int> numbers = new List<int>();
numbers.Add(5);
numbers.Remove(5);
Console.WriteLine(numbers.Count);
Real-world use case:
Use ICollection<T> when you need to manipulate the collection (add/remove items),
such as managing an in-memory cart of products in a shopping application.
C# Collections C# Programming Tutorial · Collections
Example:
bool hasItem = numbers.Contains(10);
int index = numbers.IndexOf(10);
var result = numbers.Find(x => x > 50);C# Collections C# Programming Tutorial · Collections
Answer: The average time complexity is O(1) (constant time), thanks to hash-based indexing. However, in worst-case scenarios (rare), it can degrade to O(n).
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Use the Peek() method to view the front element without removing it.
Example:
Queue<string> tasks = new Queue<string>();
tasks.Enqueue("Task1");
string nextTask = tasks.Peek(); // Returns "Task1", does not remove
it
Useful when you want to see what’s next without modifying the queue.
C# Collections C# Programming Tutorial · Collections
Example:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class EmployeeCollection : Collection<Employee>
{
// You can add custom methods specific to Employee collection
here
}
Or simply use List<Employee> directly for flexibility.
C# Collections C# Programming Tutorial · Collections
Use methods like ToList(), ToArray(), or ToDictionary() to convert LINQ query
results to different collection types.
Examples:
var numbers = new int[] { 1, 2, 3, 4, 5 };
// Convert to List<int>
List<int> numberList = numbers.ToList();
// Convert to array
int[] numberArray = numberList.ToArray();
// Convert to dictionary (key = number, value = square)
Dictionary<int, int> numberDict = numbers.ToDictionary(n => n, n =>
n * n);
📘 C# Thread-Safe Collections –
Interview Questions & AnswersC# Collections C# Programming Tutorial · Collections
Answer: Use the Peek() method. Example: int top = stack.Peek(); This is useful when you just want to inspect the top element without altering the stack.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
You can use a foreach loop over KeyValuePair<TKey, TValue> elements, which
iterates in sorted key order:
foreach (var kvp in sortedList)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
You can also iterate over keys or values separately:
foreach (var key in sortedList.Keys) { /* ... */ }
foreach (var value in sortedList.Values) { /* ... */ }
📘 C# SortedSet<T> – Interview
Questions & Answers
C# Collections C# Programming Tutorial · Collections
Answer: Use a foreach loop which iterates over the elements in sorted ascending order: foreach (var item in sortedSet) { Console.WriteLine(item); }
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: No, HashSet<T> does not allow duplicates. Attempting to add a duplicate value will return false and not change the set. bool added = uniqueNumbers.Add(2); // returns false because 2 lready exists
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Adding or removing at the start or end: O(1) Adding or removing at an arbitrary position (if you already have the node reference): O(1) Searching for a node by value: O(n), because traversal is required
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
IList<T> extends ICollection<T> and allows:
Example:
IList<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Insert(0, "Banana"); // Insert at index 0
Console.WriteLine(fruits[1]); // Access by index
Real-world use case:
Use IList<T> when order matters and you need to access, insert, or remove elements at
specific positions, like reordering tasks in a to-do list.
C# Collections C# Programming Tutorial · Collections
Peek() returns the top element without removing it. It’s helpful for:
Example:
if (stack.Count > 0)
{
var current = stack.Peek();
}
Throws InvalidOperationException if the stack is empty.
C# Collections C# Programming Tutorial · Collections
Dictionary?
Feature TryGetValue() Indexer (dictionary[key])
Safe? Yes – avoids exception No – throws if key doesn't exist
Returns Boolean (and output
value)
Direct value
Use
case
When unsure if key exists When key is guaranteed to
exist
Example:
if (dictionary.TryGetValue("Bob", out int age)) {
Console.WriteLine(age);
}
// dictionary["Unknown"]; // throws KeyNotFoundException if missing
C# Collections C# Programming Tutorial · Collections
Feature TryGetValue() Indexer (dictionary[key])
Safe? Yes – avoids exception No – throws if key doesn't exist
Returns Boolean (and output
value)
Direct value
Use
case
When unsure if key exists When key is guaranteed to
exist
Example:
if (dictionary.TryGetValue("Bob", out int age)) {
Console.WriteLine(age);
// dictionary["Unknown"]; // throws KeyNotFoundException if missing
C# Collections C# Programming Tutorial · Collections
Answer: Method Purpose dd() Adds one item ddRange () dds multiple items (collection) Example: list.Add(1); // One item list.AddRange(new[] { 2, 3, 4 }); // Multiple
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
These interfaces provide read-only access to collections:
Example:
IReadOnlyList<int> ids = new List<int> { 1, 2, 3 };
Console.WriteLine(ids[0]); // Access element
// ids[0] = 10; // Compile-time error – read-only
Real-world use case:
Useful in APIs where you want to expose collection data but prevent consumers from
modifying it—e.g., returning a list of supported currencies from a service.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Clear() method to remove all elements. Example: tasks.Clear(); fter calling Clear(), the queue is empty (Count == 0).
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Union: Combines all unique elements from both sets
set1.UnionWith(set2);
set1.IntersectWith(set2);
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.UnionWith(set2); // set1 = {1, 2, 3, 4, 5}
set1.IntersectWith(set2); // set1 = {3, 4, 5}C# Collections C# Programming Tutorial · Collections
Operation LinkedList<T> List<T>
Indexed access O(n) (no indexing) O(1) (direct access)
dd/Remove at
start/end
O(1) O(n) (start), O(1) (end)
dd/Remove in middle O(1) (with node ref) O(n) (shifts elements)
Memory overhead Higher (extra pointers) Lower (array storage)
Summary:
Use LinkedList<T> when you need fast insertions/deletions anywhere and don’t require
indexed access. Use List<T> for fast random access and better memory efficiency.
📘 C# SortedList<TKey, TValue> –
Interview Questions & AnswersC# Collections C# Programming Tutorial · Collections
Answer: Due to the underlying balanced tree structure, these operations have O(log n) time complexity. 📘 C# Collection Initializers & LINQ – Interview Questions & Answers
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
IComparer.
Example:
SortedList<int, string> sortedList = new SortedList<int, string>();
sortedList.Add(10, "Ten");
sortedList.Add(5, "Five");
sortedList.Add(20, "Twenty");
// Items automatically sorted by keys: 5, 10, 20
If you want to sort by custom criteria, implement an IComparer and pass it to the
SortedList constructor.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Count property. if (stack.Count == 0) { Console.WriteLine("Stack is empty"); } Unlike some languages, C# stacks do not provide an IsEmpty property.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Example:
foreach (var key in dictionary.Keys)
Console.WriteLine(key);
foreach (var value in dictionary.Values)
Console.WriteLine(value);
C# Collections C# Programming Tutorial · Collections
Answer: Insert(index, item) adds an item at a specific index. Add(item) adds to the end of the list. Example: list.Insert(0, 99); // Add at beginning list.Add(100); // Add at end
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Method Purpose Return Value dd(item) Adds item if not already present true if added, false if duplicate Contains(it em) Checks if item exists in the set true if found, false otherwise
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use a foreach loop. Iteration does not modify the queue. Example: foreach (var order in orders) { Console.WriteLine(order); } You can also use .ToArray() if needed: string[] items = orders.ToArray();
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: dd()? Insert(index, item) adds an item at a specific index. Add(item) adds to the end of the list. Example: list.Insert(0, 99); // Add at beginning list.Add(100); // Add at end
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Feature Non-Generic Generic
Type Safety No Yes
Performanc
Slower (boxing/unboxing) Faster
Casting Required Not required
Syntax Less readable Clean and
type-specific
Examples:
// Non-generic
rrayList arr = new ArrayList();
rr.Add(1);
rr.Add("text"); // Allowed, but risky
// Generic
List<int> list = new List<int>();
list.Add(1);
// list.Add("text"); // Compile-time error
// Hashtable vs Dictionary
Hashtable ht = new Hashtable();
ht["id"] = 101;
Dictionary<string, int> dict = new Dictionary<string, int>();
dict["id"] = 101;
Real-world use case:
Generic collections are recommended for new development due to safety and performance.
Non-generic collections are often found in older legacy systems.
C# Collections C# Programming Tutorial · Collections
Example:
dictionary.Add("John", 25);
dictionary.Add("John", 30); // Exception
dictionary["John"] = 30; // Overwrites the value safelyC# Collections C# Programming Tutorial · Collections
Answer: Again, use the Peek() method: var front = queue.Peek(); Difference from Dequeue(): Peek() returns the front element without removing it. Dequeue() returns and removes the front element. 📘 C# Stack<T> – Interview Questions &
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use a foreach loop; the iteration order is not guaranteed. foreach (var item in uniqueNumbers) { Console.WriteLine(item); } 📘 C# LinkedList<T> – Interview Questions & Answers
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Sort() method or provide a custom comparer. Example: list.Sort(); // Default sort (ascending) list.Sort((a, b) => b.CompareTo(a)); // Descending
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Clear() method to remove all elements. stack.Clear(); fter this, Count becomes 0, and the internal array is reset.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Feature IEnumerable
<T>
ICollection<T>
Read-only Yes No
Modification Not supported Supports Add, Remove,
Clear
Count property No Yes (Count)
Example:
IEnumerable<string> names = new List<string> { "A", "B" };
// names.Add("C"); // Error
ICollection<string> nameCollection = new List<string> { "A", "B" };
nameCollection.Add("C"); // Allowed
Real-world scenario:
Use IEnumerable<T> for read-only, query-focused tasks like LINQ. Use
ICollection<T> when managing and modifying the collection.
C# Collections C# Programming Tutorial · Collections
Use a foreach loop with KeyValuePair<TKey, TValue>:
foreach (KeyValuePair<string, int> pair in dictionary)
{
Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
}
Or use deconstruction (C# 7+):
foreach (var (key, value) in dictionary)
{
Console.WriteLine($"{key} = {value}");
}C# Collections C# Programming Tutorial · Collections
Answer: Use the Reverse() method. Example: list.Reverse(); Use case: Reversing order of recent messages or results.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Use a foreach loop, which iterates from top to bottom (LIFO order).
Example:
foreach (var item in stack)
{
Console.WriteLine(item);
}
This does not modify the stack — it's read-only iteration.
📘 C# HashSet<T> – Interview Questions
& Answers
C# Collections C# Programming Tutorial · Collections
Feature List<T> ArrayList
Generic Yes No
Type Safety Compile-time Runtime (casting required)
Performanc
Better (no boxing) Slower for value types (boxing)
Example:
List<int> list = new List<int>();
list.Add(10); // Type-safe
rrayList arrayList = new ArrayList();
rrayList.Add(10);
int num = (int)arrayList[0]; // Casting required
Best Practice:
lways prefer List<T> in new code. Use ArrayList only when working with legacy
systems.
C# Collections C# Programming Tutorial · Collections
rgumentNullException.
This restriction ensures the integrity of hashing, which is used internally by the dictionary.
C# Collections C# Programming Tutorial · Collections
You can iterate using:
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Use the Clear() method to remove all elements. Example: list.Clear();
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
KeyValuePair<TKey, TValue> represents a single item in a dictionary — a key-value
pair.
Used in:
Example:
foreach (KeyValuePair<string, int> entry in dictionary)
{
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}C# Collections C# Programming Tutorial · Collections
Answer: Method Returns Find() First match FindAll () ll matches in a new list Example: var firstEven = list.Find(x => x % 2 == 0); var allEvens = list.FindAll(x => x % 2 == 0);
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Contains(item) checks whether the item exists in the list. It uses Equals() internally. Example: bool exists = list.Contains(10); Note: For custom objects, override Equals() and GetHashCode().
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Clear() method to remove all key-value pairs. dictionary.Clear(); This resets the dictionary to an empty state. 📘 C# Queue<T> – Interview Questions &
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Clear() method to remove all key-value pairs. dictionary.Clear(); This resets the dictionary to an empty state. 📘 C# Queue<T> – Interview Questions &
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Capacity is the number of elements the list can hold before resizing. It is greater than or equal to Count. Example: list.Capacity = 100; // Optional performance tuning
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Property Meaning Count Number of elements currently in the list Capacit Total allocated slots (memory reserved) Example: Console.WriteLine($"Count: {list.Count}, Capacity: {list.Capacity}");
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use GroupBy, Distinct, or nested loops. Example: bool hasDuplicates = list.Count != list.Distinct().Count();
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use ToArray() method. Example: int[] array = list.ToArray(); Useful when interfacing with APIs that require arrays.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: list = list.Distinct().ToList(); For custom objects, override Equals() and GetHashCode().
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use IndexOf(item) or FindIndex(predicate). Example: int index = list.IndexOf(10); int indexByCondition = list.FindIndex(x => x > 100); 📘 C# Dictionary<TKey, TValue> – Interview Questions & Answers
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# MNC Coding Interview C# Programming Tutorial · MNC Coding
Remove duplicates without using LINQ Distinct()
What interviewers test
Real-world scenario
You are processing millions of user IDs coming from logs or Kafka messages.
You must remove duplicates fast and predictably.
Optimized approach (HashSet)
public static List<int> RemoveDuplicates(int[] input)
{
var seen = new HashSet<int>();
var result = new List<int>();
foreach (var item in input)
{
if (seen.Add(item)) // Add returns false if already exists
{
result.Add(item);
}
}
return result;
}
Complexity
Aspect Value
Time O(n)
Space O(n) (hash storage)
Why this is better than naive loops
Interview Tip:
Say “I prefer HashSet because it gives O(1) average lookup and preserves intent clearly.”
C# MNC Coding Interview C# Programming Tutorial · MNC Coding
Explain async / await with a real production
scenario
What interviewers test
Real-world scenario
API calls:
Blocking threads = server collapse under load
Bad (Blocking)
public string GetUser()
{
var response = httpClient.GetAsync(url).Result; // Blocks thread
return response.Content.ReadAsStringAsync().Result;
}
Good (Async, scalable)
public async Task<string> GetUserAsync()
{
var response = await httpClient.GetAsync(url);
return await response.Content.ReadAsStringAsync();
}
Why async/await matters
Key interview line
“Async doesn’t make code faster; it makes servers scalable.”
C# MNC Coding Interview C# Programming Tutorial · MNC Coding
IEnumerable vs ICollection vs IList
What interviewers test
Hierarchy
IEnumerable
└── ICollection
└── IList
IEnumerable<T>
IEnumerable<int> numbers = GetNumbers();
foreach (var n in numbers) { }
✅ Best for streaming, read-only, deferred execution
ICollection<T>
ICollection<int> list = new List<int>();
list.Add(1);
✅ When modifying collection without index access
IList<T>
IList<int> list = new List<int>();
int first = list[0];
✅ When order & index matter
Interview rule of thumb
“Expose the least powerful interface required.”
C# MNC Coding Interview C# Programming Tutorial · MNC Coding
Logic
string input = "swiss";
Dictionary<char, int> map = new Dictionary<char, int>();
foreach (char c in input)
map[c] = map.ContainsKey(c) ? map[c] + 1 : 1;
foreach (char c in input)
{
if (map[c] == 1)
{
Console.WriteLine(c);
break;
}
}C# MNC Coding Interview C# Programming Tutorial · MNC Coding
Handle millions of records efficiently
What interviewers test
❌ Bad (Loads everything)
var users = db.Users.ToList(); // Memory explosion
✅ Streaming (Best)
await foreach (var user in db.Users.AsAsyncEnumerable())
{
Process(user);
}
✅ Batching
const int batchSize = 1000;
for (int i = 0; i < total; i += batchSize)
{
var batch = GetBatch(i, batchSize);
ProcessBatch(batch);
}
Key principles
C# MNC Coding Interview C# Programming Tutorial · MNC Coding
Dependency Injection without any framework
What interviewers test
Step 1: Abstraction
public interface IMessageService
{
void Send(string message);
}
Step 2: Implementation
public class EmailService : IMessageService
{
public void Send(string message)
{
Console.WriteLine("Email: " + message);
}
}
Step 3: Injection
public class Notification
{
private readonly IMessageService _service;
public Notification(IMessageService service)
{
_service = service;
}
public void Notify(string msg)
{
_service.Send(msg);
}
}
Why this matters
C# MNC Coding Interview C# Programming Tutorial · MNC Coding
struct vs class (real-world)
What interviewers test
Use struct when:
public readonly struct Point
{
public int X { get; }
public int Y { get; }
}
Use class when:
public class User
{
public string Name { get; set; }
}
Interview statement
“Structs live on stack or inline, classes live on heap with GC cost.”
C# MNC Coding Interview C# Programming Tutorial · MNC Coding
Design a rate limiter
What interviewers test
Token bucket (simple)
public class RateLimiter
{
private readonly int _limit;
private int _count;
private DateTime _windowStart = DateTime.UtcNow;
private readonly object _lock = new();
public RateLimiter(int limit)
{
_limit = limit;
}
public bool Allow()
{
lock (_lock)
{
if ((DateTime.UtcNow - _windowStart).TotalSeconds >= 1)
{
_count = 0;
_windowStart = DateTime.UtcNow;
}
if (_count < _limit)
{
_count++;
return true;
}
return false;
}
}
}
Used in
C# MNC Coding Interview C# Programming Tutorial · MNC Coding
LINQ vs IQueryable
What interviewers test
LINQ (IEnumerable)
var data = users.Where(x => x.Age > 30).ToList();
IQueryable
var data = db.Users.Where(x => x.Age > 30);
Interview line
“IQueryable builds expressions; IEnumerable executes them.”
🔟 Write clean, production-ready C# code
What interviewers test
Principles
public class OrderService
{
public void PlaceOrder(Order order)
{
if (order == null)
throw new ArgumentNullException(nameof(order));
Validate(order);
Save(order);
}
private void Validate(Order order)
{
if (order.Total <= 0)
throw new InvalidOperationException("Invalid total");
}
private void Save(Order order)
{
// persistence logic
}
}C# OOP C# Programming Tutorial · OOP
functionality.
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: OOP is a programming paradigm that organizes software around objects, which contain data (fields/properties) and behavior (methods/functions). Helps model real-world entities and their interactions.
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: Promotes code reusability through classes and objects. Easier to maintain and extend large applications. Models real-world problems better. Supports modularity, abstraction, and encapsulation, which procedural programming lacks.
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: class Vehicle {} // Base class Car : Vehicle {} // Single/Multilevel class Bike : Vehicle {} // Hierarchical
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
C# OOP C# Programming Tutorial · OOP
overloading/overriding).
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: A blueprint or template for creating objects. Defines properties (data) and methods (behavior) that the objects will have. public class Car { public string Model { get; set; } public void Start() { Console.WriteLine("Car started"); } }
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: An instance of a class with actual values. Represents a real-world entity in memory. Car myCar = new Car(); // Object of Car class
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: Feature Class Object Definition Blueprint/Template Instance of a class Memory Does not occupy memory Occupies memory Example class Car { } Car myCar = new Car();
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: A special method used to initialize objects when they are created. Has the same name as the class and no return type. public class Car { public string Model; public Car(string model) { Model = model; } } Car car = new Car("Tesla");
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
~Car() { Console.WriteLine("Car object destroyed"); }
C# OOP C# Programming Tutorial · OOP
Answer: Instance members → Belong to each object, require object to access. Static members → Belong to the class itself, shared by all objects. public class Car { public string Model; // Instance public static int Count; // Static }
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: The practice of hiding internal details of a class and exposing only necessary functionality through access modifiers and properties. private int speed; public int Speed { get { return speed; } set { speed = value; } }
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: Hiding implementation details and showing only the essential features of an object. Achieved using abstract classes and interfaces. bstract class Vehicle { public abstract void Start(); }
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
properties and methods from another class (base/parent).
class Vehicle { public void Start() => Console.WriteLine("Vehicle
started"); }
class Car : Vehicle { } // Car inherits from VehicleC# OOP C# Programming Tutorial · OOP
Answer: Ability of an object to take multiple forms. Types: Compile-time (method overloading) Run-time (method overriding) Vehicle v = new Car(); v.Start(); // Run-time polymorphism
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: Car object: Class → Car Objects → myCar, yourCar Properties → Color, Model, Speed Methods → Start(), Stop(), Accelerate() Shows encapsulation, inheritance (e.g., ElectricCar : Car), and polymorphism in ction.
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
exposing only necessary functionalities.
modified.
Example: A BankAccount class hides its balance and only allows deposit/withdraw
operations:
private decimal balance;
public void Deposit(decimal amount) { if(amount > 0) balance +=
mount; }
C# OOP C# Programming Tutorial · OOP
Example: Prevent withdrawing more than the account balance:
public void Withdraw(decimal amount)
{
if (amount <= balance) balance -= amount;
else throw new InvalidOperationException("Insufficient
balance");
}C# OOP C# Programming Tutorial · OOP
private int age;
public int Age
{
get { return age; }
set { if (value > 0) age = value; }
}C# OOP C# Programming Tutorial · OOP
C# OOP C# Programming Tutorial · OOP
Example:
private decimal balance; // hidden
public decimal Balance { get { return balance; } } // read-only
ccess
C# OOP C# Programming Tutorial · OOP
Example:
protected string accountType; // accessible in derived classes
internal string branchCode; // accessible within same assemblyC# OOP C# Programming Tutorial · OOP
Answer: Technically yes, but not recommended. Makes the data vulnerable to invalid modifications. Encapsulation recommends private fields + public properties.
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Example:
private int score;
public int Score
{
get { return score; }
set { if (value >= 0) score = value; } // validation
}C# OOP C# Programming Tutorial · OOP
Answer: Encapsulation → Hides internal data, focuses on data protection. Abstraction → Hides implementation details, focuses on simplifying complex systems.
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Real-World Example: Bank Account Management
public class BankAccount
{
private string accountNumber; // private field
private decimal balance; // private field
public string AccountNumber { get { return accountNumber; } } //
read-only
public decimal Balance { get { return balance; } } //
read-only
public BankAccount(string accNum, decimal initialBalance)
{
ccountNumber = accNum;
balance = initialBalance >= 0 ? initialBalance : throw new
rgumentException("Invalid balance");
}
public void Deposit(decimal amount)
{
if(amount > 0) balance += amount;
else throw new ArgumentException("Deposit must be
positive");
}
public void Withdraw(decimal amount)
{
if(amount > 0 && amount <= balance) balance -= amount;
else throw new InvalidOperationException("Insufficient
balance");
}
}
// Usage
BankAccount myAccount = new BankAccount("ACC123", 1000);
myAccount.Deposit(500); // Balance becomes 1500
myAccount.Withdraw(200); // Balance becomes 1300
Console.WriteLine($"Account: {myAccount.AccountNumber}, Balance:
{myAccount.Balance}");
Explanation:
C# OOP C# Programming Tutorial · OOP
system and exposing only the essential features.
Example: A Vehicle class exposes Start() method without revealing engine details.
C# OOP C# Programming Tutorial · OOP
Answer: Simplifies complex systems by exposing only relevant functionality. Enhances maintainability, readability, and reusability of code. Reduces dependency on implementation details, making systems more flexible.
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: Using abstract classes or interfaces. Abstract classes can have abstract and non-abstract methods. Interfaces define method signatures only. bstract class Vehicle { public abstract void Start(); } interface IDriveable { void Drive(); }
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
(without implementation).
bstract class Animal
{
public abstract void MakeSound();
public void Sleep() => Console.WriteLine("Sleeping");
}C# OOP C# Programming Tutorial · OOP
Answer: Interfaces define a contract of methods, properties, or events that implementing classes must follow. Interfaces provide full abstraction without any implementation (C# 8+ allows default methods). interface IFlyable { void Fly(); }
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
nd decoupling.
class Bird : IFlyable
{
public void Fly() => Console.WriteLine("Bird is flying");
}
class Airplane : IFlyable
{
public void Fly() => Console.WriteLine("Airplane is flying");
}C# OOP C# Programming Tutorial · OOP
Feature Abstract Class Interface
Methods Can have abstract +
concrete methods
Only abstract methods (C# 8+ allows default
implementation)
Fields Can have fields Cannot have fields
Inheritance Single inheritance Multiple interfaces can be implemented
Constructo
Can have constructors Cannot have constructors
C# OOP C# Programming Tutorial · OOP
bstract class Shape { public abstract void Draw(); }
// Shape s = new Shape(); // Not allowed
class Circle : Shape { public override void Draw() =>
Console.WriteLine("Circle"); }
C# OOP C# Programming Tutorial · OOP
Answer: Yes, constructors are used to initialize fields in derived classes. bstract class Vehicle { protected string Brand; public Vehicle(string brand) { Brand = brand; } } class Car : Vehicle { public Car(string brand) : base(brand) { } }
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: Yes, abstract classes can have concrete methods with implementation. Allows shared behavior for derived classes. bstract class Animal { public void Sleep() => Console.WriteLine("Sleeping"); public abstract void MakeSound(); }
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: Reduces system complexity by focusing on essential features. Decouples modules, making large systems easier to maintain and extend. Promotes code reuse and flexibility.
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Answer: Hides implementation details, exposing only what is necessary. Users interact with interfaces or abstract methods, not the full system logic. Simplifies testing, maintenance, and understanding of code.
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# OOP C# Programming Tutorial · OOP
Real-World Example: Payment Processing
// Abstract class
bstract class Payment
{
public abstract void Pay(decimal amount);
public void ShowReceipt(decimal amount) =>
Console.WriteLine($"Paid: {amount:C}");
}
// Derived classes implement abstraction
class CreditCardPayment : Payment
{
public override void Pay(decimal amount) =>
Console.WriteLine($"Paid {amount:C} using Credit Card");
}
class PayPalPayment : Payment
{
public override void Pay(decimal amount) =>
Console.WriteLine($"Paid {amount:C} using PayPal");
}
// Usage
Payment payment1 = new CreditCardPayment();
payment1.Pay(500);
payment1.ShowReceipt(500);
Payment payment2 = new PayPalPayment();
payment2.Pay(300);
payment2.ShowReceipt(300);
Explanation:
made.
C# OOP C# Programming Tutorial · OOP
Answer: Base Class (Parent) → Class whose members are inherited. Derived Class (Child) → Class that inherits from base class. class Vehicle { public void Start() {} } // Base class Car : Vehicle {} // Derived
In a production C# OOP application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.