Interview Q&A

Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.

By tech stack (from PDF library)

C# Programming Tutorial · CLR & types

Short answer: CLR & types is essential when working with C# Programming Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in C# Programming projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does CLR & types solve?
  • What tools or APIs do you use (.NET ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

C# Programming Tutorial · ASP.NET Core

Short answer: ASP.NET Core is essential when working with C# Programming Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in C# Programming projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does ASP.NET Core solve?
  • What tools or APIs do you use (.NET ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

C# Programming Tutorial · EF Core

Short answer: EF Core is essential when working with C# Programming Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in C# Programming projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does EF Core solve?
  • What tools or APIs do you use (.NET ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

C# Programming Tutorial · Security

Short answer: Security is essential when working with C# Programming Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in C# Programming projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does Security solve?
  • What tools or APIs do you use (.NET ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

C# Programming Tutorial · Testing

Short answer: Testing is essential when working with C# Programming Tutorial. Interviewers want to hear clear definitions, trade-offs, and a concise example from your experience.

How to structure your answer

  1. Define the concept in one or two sentences.
  2. Explain how it applies in C# Programming projects.
  3. Give an example from work, internships, or a personal project.
  4. Mention trade-offs—what you gain and what you sacrifice.

Example talking points

  • What problem does Testing solve?
  • What tools or APIs do you use (.NET ecosystem)?
  • How do you test or monitor this area?

Tip: Keep answers under 90 seconds unless the interviewer asks for depth. Practice aloud on Toolliyo before your mock interview.

Permalink

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.

Permalink

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:

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

int Fibonacci(int n)

if (n <= 1) return n;

int a = 0, b = 1;

for (int i = 2; i <= n; i++)

int temp = a + b;

a = b;

b = temp;

return b;

Explanation:

Iterative DP approach; each Fibonacci number is sum of two previous.

Follow on:

Permalink

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).

Permalink

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:

Permalink

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.

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

Algorithm

int GCD(int a, int b)

Follow on:

while (b != 0)

int temp = b;

b = a % b;

a = temp;

return a;

Explanation:

Repeatedly replace (a, b) with (b, a mod b) until b is 0; then a is the GCD.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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++;

Permalink

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:

Permalink

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:

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

int LCM(int a, int b)

return a / GCD(a, b) * b;

Explanation:

LCM × GCD = product of the two numbers.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

int ClimbStairs(int n) {

if (n <= 2) return n;

int a = 1, b = 2;

for (int i = 3; i <= n; i++) {

int c = a + b;

a = b;

b = c;

return b;

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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:

Permalink

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.

Permalink

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).

Permalink

C# Coding Interview C# Programming Tutorial · Coding

public bool HaveOppositeSigns(int x, int y) {

return (x ^ y) < 0;

Explanation:

XOR of two numbers with opposite signs has the sign bit set (negative number).

Permalink

C# Coding Interview C# Programming Tutorial · Coding

x * half * half : (half * half) / x;

Explanation:

Uses fast exponentiation (divide and conquer) to calculate x^n in O(log n).

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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:

Permalink

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.

Permalink

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.

Permalink

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).

Permalink

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:

Permalink

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.

Permalink

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;

Permalink

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:

Permalink

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.

Permalink

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];

Permalink

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.

Permalink

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:

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

headB : a.next;

b = (b == null) ? headA : b.next;

return a; // either intersection or null

Explanation:

Two pointers traverse both lists; if no intersection, both will reach null simultaneously.

Permalink

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:

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

int SumOfDigits(int n)

int sum = 0;

n = Math.Abs(n);

while (n > 0)

sum += n % 10;

n /= 10;

return sum;

Explanation:

Extract digits using modulo 10 and add.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

public void Swap(ref int a, ref int b) {

if (a != b) {

a ^= b;

b ^= a;

a ^= b;

Explanation:

XOR swap algorithm exchanges values without extra storage. (Check a != b to avoid

zeroing when both are same.)

Permalink

C# Coding Interview C# Programming Tutorial · Coding

bool IsRotation(string s1, string s2)

if (s1.Length != s2.Length) return false;

string doubled = s1 + s1;

return doubled.Contains(s2);

Follow on:

Explanation:

If s2 is rotation of s1, it must be substring of s1+s1.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

appears twice except one

public int SingleNumber(int[] nums) {

int result = 0;

foreach (var num in nums) {

result ^= num;

return result;

Explanation:

XOR of all elements cancels duplicates, leaving the single unique element.

Permalink

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).

Permalink

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:

Permalink

C# Coding Interview C# Programming Tutorial · Coding

Amount)

int CoinChange(int[] coins, int amount)

int[] dp = new int[amount + 1];

Array.Fill(dp, amount + 1);

dp[0] = 0;

for (int i = 1; i <= amount; i++)

foreach (int coin in coins)

if (coin <= i)

dp[i] = Math.Min(dp[i], 1 + dp[i - coin]);

return dp[amount] > amount ? -1 : dp[amount];

Explanation:

Bottom-up DP: min coins needed for all amounts up to target.

Follow on:

Permalink

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.

Permalink

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.

Permalink

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];

Permalink

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:

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

Array

int LongestConsecutive(int[] nums)

HashSet<int> set = new HashSet<int>(nums);

int longest = 0;

foreach (int num in set)

if (!set.Contains(num - 1))

Follow on:

int currentNum = num;

int length = 1;

while (set.Contains(currentNum + 1))

currentNum++;

length++;

longest = Math.Max(longest, length);

return longest;

Explanation:

Check only starts of sequences, count consecutive numbers using HashSet for O(n).

Permalink

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:

Permalink

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.

Permalink

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];

Permalink

C# Coding Interview C# Programming Tutorial · Coding

int TrailingZeroes(int n)

int count = 0;

for (int i = 5; i <= n; i *= 5)

count += n / i;

return count;

Explanation:

Trailing zeros come from factors of 10 = 2 × 5, but 2s are plenty, count 5s.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

All Characters of String t

string MinWindow(string s, string t)

if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t)) return

"";

Dictionary<char, int> dictT = new Dictionary<char, int>();

foreach (char c in t)

dictT[c] = dictT.ContainsKey(c) ? dictT[c] + 1 : 1;

int required = dictT.Count;

int formed = 0;

Dictionary<char, int> windowCounts = new Dictionary<char,

int>();

int left = 0, right = 0;

int minLen = int.MaxValue, minLeft = 0;

while (right < s.Length)

char c = s[right];

windowCounts[c] = windowCounts.ContainsKey(c) ?

windowCounts[c] + 1 : 1;

if (dictT.ContainsKey(c) && windowCounts[c] == dictT[c])

formed++;

while (left <= right && formed == required)

if (right - left + 1 < minLen)

minLen = right - left + 1;

Follow on:

minLeft = left;

char leftChar = s[left];

windowCounts[leftChar]--;

if (dictT.ContainsKey(leftChar) &&

windowCounts[leftChar] < dictT[leftChar])

formed--;

left++;

right++;

return minLen == int.MaxValue ? "" : s.Substring(minLeft,

minLen);

Explanation:

Sliding window with two pointers keeps track of counts of chars matching the target.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

public int TrailingZeroes(int n) {

int count = 0;

while (n > 0) {

n /= 5;

count += n;

return count;

Explanation:

Count factors of 5 in factorial since 2s are plentiful, trailing zeros depend on 5s.

Permalink

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.

Permalink

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.

Permalink

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];

Permalink

C# Coding Interview C# Programming Tutorial · Coding

1 : -1;

return candidate;

Explanation:

Boyer-Moore Voting Algorithm tracks majority element by counting net votes.

Follow on:

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

1 : -1;

return candidate;

Explanation:

Maintain a candidate and count; majority element survives this cancellation.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

x * temp * temp : (temp * temp) / x;

Explanation:

Recursive fast power divides exponent by 2 to reduce complexity to O(log n).

Permalink

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();

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

int CountOnes(int n)

int count = 0;

while (n != 0)

n &= (n - 1); // drops the lowest set bit

count++;

return count;

Explanation:

Brian Kernighan’s algorithm removes one set bit per iteration.

Permalink

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°.

Permalink

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.

Permalink

C# Coding Interview C# Programming Tutorial · Coding

a / b : throw new DivideByZeroException(),

_ => throw new ArgumentException("Invalid operator"),

Explanation:

Simple switch statement performing basic arithmetic, with divide-by-zero check.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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:

Permalink

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.

Permalink

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.

Permalink

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

Permalink

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.

Permalink

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.

Permalink

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

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

List<string> fruits = new List<string> { "Apple", "Banana" };

foreach (var fruit in fruits)

Console.WriteLine(fruit);

Permalink

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.

Follow:

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);

Permalink

C# Collections C# Programming Tutorial · Collections

  • Use the Stopwatch class from System.Diagnostics to time operations

accurately.

  • Profile your code using tools like Visual Studio Profiler, dotTrace, or PerfView for

deeper insights.

  • Measure specific operations like add, remove, search, or iteration by running them

multiple times and averaging results.

Example:

var stopwatch = Stopwatch.StartNew();

list.Add(1000);

stopwatch.Stop();

Console.WriteLine($"Add operation took {stopwatch.ElapsedTicks}

ticks");

Permalink

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).

  • Supports atomic operations like adding, updating, and removing items.
  • Useful in multi-threaded scenarios where data integrity and performance are critical.

Example:

ConcurrentDictionary<int, string> concurrentDict = new

ConcurrentDictionary<int, string>();

concurrentDict.TryAdd(1, "One");

concurrentDict.TryUpdate(1, "Uno", "One");

Permalink

C# Collections C# Programming Tutorial · Collections

To implement a custom collection:

  • Derive from existing base classes like Collection<T>, List<T>, or implement

interfaces such as ICollection<T>, IEnumerable<T>, or IList<T>.

  • Override or implement necessary methods like Add(), Remove(),

GetEnumerator(), and indexers.

  • Provide custom behavior, validation, or constraints as needed.

Example:

public class MyCustomCollection<T> : Collection<T>

protected override void InsertItem(int index, T item)

Follow:

// Custom validation

if (item == null) throw new

ArgumentNullException(nameof(item));

base.InsertItem(index, item);

Permalink

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.

  • Allows efficient insertions and deletions anywhere in the list.
  • Does not support indexed access like List<T>.

Example:

LinkedList<int> numbers = new LinkedList<int>();

numbers.AddLast(10);

numbers.AddLast(20);

Permalink

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:

  • You need a resizable array-like structure
  • You want to perform frequent insertions, deletions, and searches

Example:

List<string> names = new List<string>();

names.Add("Alice");

Permalink

C# Collections C# Programming Tutorial · Collections

SortedList<TKey, TValue> is a collection of key-value pairs that maintains the

elements sorted by keys.

  • Implements both IDictionary<TKey, TValue> and

IList<KeyValuePair<TKey, TValue>>.

  • Keys are automatically sorted in ascending order based on their natural comparer

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.

Permalink

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.

Permalink

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.

  • Keys must be unique
  • Keys must be non-null (for reference types)
  • Values can be null if the type allows it

Example:

Dictionary<string, int> ages = new Dictionary<string, int>();

ages.Add("Alice", 30);

ages.Add("Bob", 25);

Use case: Storing user profiles by ID, or mapping product names to prices.

Permalink

C# Collections C# Programming Tutorial · Collections

SortedSet<T> is a collection that stores unique elements in sorted order.

  • Implements a self-balancing binary search tree (usually a Red-Black Tree).
  • Automatically maintains elements in ascending sorted order.
  • Provides set operations like union, intersection, and difference.

Example:

SortedSet<int> sortedSet = new SortedSet<int> { 5, 1, 3 };

sortedSet.Add(2); // Sorted order maintained: {1, 2, 3, 5}

Follow:

Permalink

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.

  • The first item added is the first to be removed.
  • It is part of the System.Collections.Generic namespace.

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");

Permalink

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

ArrayList 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.

Permalink

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.

  • The last element added is the first one removed
  • Belongs to System.Collections.Generic

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

Permalink

C# Collections C# Programming Tutorial · Collections

Feature HashSet<T> List<T> Dictionary<TKey,

TValue>

Allows

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)

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

  • Collection<T> is a base class for creating custom collections.
  • It wraps an IList<T> internally and provides virtual methods for insert, remove, and

clear, allowing easy customization.

  • Unlike List<T>, which is optimized for performance, Collection<T> focuses on

extensibility.

  • Useful when you want to create a collection with customized behaviors (e.g.,

validation, event firing).

Permalink

C# Collections C# Programming Tutorial · Collections

  • 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

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Add() method or the indexer []:

// Using Add()

dictionary.Add("key1", "value1");

// Using indexer

dictionary["key2"] = "value2";

Follow:

Note: Add() throws an exception if the key already exists, while indexer will overwrite the

value.

Permalink

C# Collections C# Programming Tutorial · Collections

Follow:

  • List<T> uses a contiguous array internally, so memory is compact and

cache-friendly.

  • LinkedList<T> stores elements in nodes with extra pointers (Next and

Previous), leading to more memory overhead.

  • Therefore, List<T> generally has lower memory usage and better cache

performance than LinkedList<T>, especially for large collections.

Permalink

C# Collections C# Programming Tutorial · Collections

Follow:

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)

Permalink

C# Collections C# Programming Tutorial · Collections

for (int i = 0; i < fruits.Count; i++)

Console.WriteLine(fruits[i]);

Permalink

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.

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

You can use the Add() or AddRange() method.

Example:

Follow:

List<int> numbers = new List<int>();

numbers.Add(10); // Add single item

numbers.AddRange(new int[] { 20, 30 }); // Add multiple

Permalink

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:

Follow:

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();

Permalink

C# Collections C# Programming Tutorial · Collections

Internally, Queue<T> uses a circular array to efficiently manage memory and operations.

  • Head pointer marks the front (next item to be dequeued).
  • Tail pointer marks where the next item will be enqueued.
  • Automatically resizes when capacity is exceeded.

This implementation ensures constant time operations for enqueue and dequeue.

Permalink

C# Collections C# Programming Tutorial · Collections

Internally, Stack<T> uses an array-based dynamic storage system:

  • When capacity is exceeded, the internal array resizes automatically (typically

doubles)

  • The top of the stack is managed with a private index pointer

This structure provides fast push and pop operations (constant time on average).

Permalink

C# Collections C# Programming Tutorial · Collections

Generic collections offer several advantages:

  • Type Safety: Compile-time checking prevents runtime errors.
  • Performance: Avoids boxing/unboxing of value types.
  • Code Clarity: Cleaner code without explicit casting.

Follow:

  • Reusability: Generic code can work with any data type.

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.

Permalink

C# Collections C# Programming Tutorial · Collections

All these operations generally have O(1) average time complexity due to the underlying

hash table structure.

Permalink

C# Collections C# Programming Tutorial · Collections

  • Use thread-safe collections provided by .NET (ConcurrentDictionary,

ConcurrentQueue, BlockingCollection, etc.).

  • Use synchronization primitives like lock, Mutex, Semaphore, or

ReaderWriterLock around critical sections when using non-thread-safe

collections.

  • Avoid shared mutable state or design the program to minimize contention.
  • Use immutable collections when possible to eliminate synchronization.
Permalink

C# Collections C# Programming Tutorial · Collections

Scenario Best Choice Trade-offs

Fast indexed

access

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

Permalink

C# Collections C# Programming Tutorial · Collections

  • IComparer<T> defines a method Compare(T x, T y) for custom sorting logic

(used in sorting operations like Sort()).

  • IEqualityComparer<T> defines methods Equals(T x, T y) and

GetHashCode(T obj) to determine equality and hashing (used in dictionaries,

Follow:

sets, etc.).

  • They allow collections to customize how items are compared or checked for equality,

beyond default implementations.

Permalink

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

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Remove(key) method:

dictionary.Remove("key1");

Returns true if the key was found and removed, false otherwise.

Permalink

C# Collections C# Programming Tutorial · Collections

Add:

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

Permalink

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.

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

  • Filter: Use Where() to select elements based on a condition.
  • Sort: Use OrderBy() or OrderByDescending().
  • Group: Use GroupBy() to group elements by a key.

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);

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

Use methods like:

  • Remove(item) – removes first occurrence
  • RemoveAt(index) – removes by index
  • RemoveAll(predicate) – removes all matching a condition
  • Clear() – removes all items

Example:

numbers.Remove(10);

numbers.RemoveAt(0);

numbers.RemoveAll(x => x > 100);

numbers.Clear();

Permalink

C# Collections C# Programming Tutorial · Collections

  • When you need a collection of unique elements in sorted order.
  • Performing range queries or retrieving elements in sorted order.
  • Implementing mathematical set operations efficiently.
  • Examples:
  • Leaderboards
  • Scheduling tasks sorted by priority
  • Auto-complete suggestions sorted alphabetically

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# Collections C# Programming Tutorial · Collections

Operation Method Description

Add Enqueue

Adds 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(); // Remove

Permalink

C# Collections C# Programming Tutorial · Collections

Follow:

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 top

Permalink

C# Collections C# Programming Tutorial · Collections

Searching by key uses binary search, so the time complexity is O(log n).

Follow:

Permalink

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)

Permalink

C# Collections C# Programming Tutorial · Collections

Add all elements from the collection to a HashSet<T>, which automatically removes

duplicates.

Follow:

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}.

Permalink

C# Collections C# Programming Tutorial · Collections

  • Concise and readable code: LINQ makes querying collections clear and

expressive.

  • Declarative style: You focus on what to retrieve, not how.
  • Powerful operations: Filtering, sorting, grouping, joining, projecting, and more.
  • Deferred execution: Queries execute only when results are needed, improving

performance.

  • Strongly typed: Compile-time checking and IntelliSense support.
Permalink

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

Additional

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.

Follow:

📘 C# Collections: Performance &

Memory Considerations – Interview Q&A

Permalink

C# Collections C# Programming Tutorial · Collections

Follow:

  • Pre-allocate capacity when you know the expected size (e.g., new

List<T>(capacity)) to avoid frequent resizing.

  • Use value types or structs when appropriate to reduce reference overhead.
  • Choose collections with lower overhead for your use case (e.g., List<T> instead of

LinkedList<T> if indexing is needed).

  • Use immutable collections or pooling to minimize allocations.
  • Avoid unnecessary boxing/unboxing by using generic collections instead of

non-generic.

  • Regularly trim collections if supported (e.g., List<T>.TrimExcess()).

📘 C# Advanced Collection Topics –

Interview Questions & Answers

Permalink

C# Collections C# Programming Tutorial · Collections

  • Deep cloning copies the collection and all objects inside it recursively.
  • Ways to deep clone:
  • Implement ICloneable in your objects with deep clone logic.
  • Use serialization (binary, XML, JSON) to serialize and deserialize objects.
  • Manually create new instances of each item.

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.

Permalink

C# Collections C# Programming Tutorial · Collections

Use a foreach loop to traverse the linked list from start to end.

foreach (var num in numbers)

Console.WriteLine(num);

Permalink

C# Collections C# Programming Tutorial · Collections

ICollection<T> extends IEnumerable<T> and adds features like:

  • Counting (Count property)
  • Adding and removing items (Add, Remove)
  • Checking for existence (Contains)

Difference:

  • IEnumerable<T> is read-only and forward-only iteration.
  • ICollection<T> adds modification capabilities.

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.

Permalink

C# Collections C# Programming Tutorial · Collections

  • ContainsKey(key) – checks for key existence
  • ContainsValue(value) – checks for value

Example:

dictionary.ContainsKey("Alice"); // true/false

dictionary.ContainsValue(30); // true/false

Permalink

C# Collections C# Programming Tutorial · Collections

Accessing an element by index is O(1) (constant time) — same as arrays.

Example:

int first = numbers[0]; // O(1)

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

Follow:

  • 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).

Permalink

C# Collections C# Programming Tutorial · Collections

  • 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.

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

Use a foreach loop which iterates over the elements in sorted ascending order:

foreach (var item in sortedSet)

Console.WriteLine(item);

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

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

already exists

Permalink

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);

Follow:

📘 C# Thread-Safe Collections –

Interview Questions & Answers

Permalink

C# Collections C# Programming Tutorial · Collections

  • Define your custom object class.

Follow:

  • Create a collection class that holds objects of that type using generics or directly.

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.

Permalink

C# Collections C# Programming Tutorial · Collections

  • 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
Permalink

C# Collections C# Programming Tutorial · Collections

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).

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

IList<T> extends ICollection<T> and allows:

  • Indexed access (like arrays)

Follow:

  • Inserting and removing at specific positions

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.

Permalink

C# Collections C# Programming Tutorial · Collections

  • Contains(item)
  • IndexOf(item)
  • Find(predicate)
  • FindAll(predicate)
  • Exists(predicate)
  • BinarySearch(item) (for sorted lists)

Example:

bool hasItem = numbers.Contains(10);

int index = numbers.IndexOf(10);

var result = numbers.Find(x => x > 50);

Permalink

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

Useful when you want to see what’s next without modifying the queue.

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Peek() method.

Example:

int top = stack.Peek();

Follow:

This is useful when you just want to inspect the top element without altering the stack.

Permalink

C# Collections C# Programming Tutorial · Collections

Due to the underlying balanced tree structure, these operations have O(log n) time

complexity.

📘 C# Collection Initializers & LINQ –

Interview Questions & Answers

Permalink

C# Collections C# Programming Tutorial · Collections

Union: Combines all unique elements from both sets

set1.UnionWith(set2);

Intersection: Keeps only elements present in both sets

set1.IntersectWith(set2);

Example:

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}

Follow:

set1.IntersectWith(set2); // set1 = {3, 4, 5}

Permalink

C# Collections C# Programming Tutorial · Collections

  • Actually, SortedList<TKey, TValue> stores key-value pairs sorted by keys.
  • To store items in a specific order, use the key to represent the sorting criteria.
  • Keys must be unique and implement IComparable or provide a custom

IComparer.

Example:

SortedList<int, string> sortedList = new SortedList<int, string>();

sortedList.Add(10, "Ten");

sortedList.Add(5, "Five");

sortedList.Add(20, "Twenty");

Follow:

// 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.

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

Operation LinkedList<T> List<T>

Indexed access O(n) (no indexing) O(1) (direct access)

Add/Remove at

start/end

O(1) O(n) (start), O(1) (end)

Add/Remove in middle O(1) (with node ref) O(n) (shifts elements)

Follow:

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 & Answers

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

These interfaces provide read-only access to collections:

  • IReadOnlyCollection<T> provides Count and enumeration.
  • IReadOnlyList<T> provides index-based access without modification.

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.

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

Method Purpose

Add() Adds one item

AddRange

Adds multiple items (collection)

Example:

list.Add(1); // One item

Follow:

list.AddRange(new[] { 2, 3, 4 }); // Multiple

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Clear() method to remove all elements.

Example:

tasks.Clear();

After calling Clear(), the queue is empty (Count == 0).

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

Peek() returns the top element without removing it. It’s helpful for:

  • Conditional checks
  • Previewing what's next
  • Preventing accidental removal

Example:

if (stack.Count > 0)

var current = stack.Peek();

Throws InvalidOperationException if the stack is empty.

Permalink

C# Collections C# Programming Tutorial · Collections

Method Purpose Return Value

Add(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

Permalink

C# Collections C# Programming Tutorial · Collections

  • dictionary.Keys – returns a collection of all keys
  • dictionary.Values – returns a collection of all values

Example:

foreach (var key in dictionary.Keys)

Console.WriteLine(key);

foreach (var value in dictionary.Values)

Follow:

Console.WriteLine(value);

Permalink

C# Collections C# Programming Tutorial · Collections

  • 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

Permalink

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

ArrayList arr = new ArrayList();

arr.Add(1);

arr.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.

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

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();

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Count property.

if (stack.Count == 0)

Console.WriteLine("Stack is empty");

Unlike some languages, C# stacks do not provide an IsEmpty property.

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Clear() method to remove all elements.

stack.Clear();

After this, Count becomes 0, and the internal array is reset.

Permalink

C# Collections C# Programming Tutorial · Collections

Use a foreach loop; the iteration order is not guaranteed.

foreach (var item in uniqueNumbers)

Console.WriteLine(item);

📘 C# LinkedList<T> – Interview

Questions & Answers

Permalink

C# Collections C# Programming Tutorial · Collections

  • Using Add() will throw a System.ArgumentException
  • Using the indexer (dictionary[key] = value) will overwrite the existing value

Example:

dictionary.Add("John", 25);

dictionary.Add("John", 30); // Exception

dictionary["John"] = 30; // Overwrites the value safely

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Sort() method or provide a custom comparer.

Example:

list.Sort(); // Default sort (ascending)

list.Sort((a, b) => b.CompareTo(a)); // Descending

Permalink

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.

Permalink

C# Collections C# Programming Tutorial · Collections

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 &

Follow:

Permalink

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

Permalink

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}");

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Reverse() method.

Example:

list.Reverse();

Follow:

Use case: Reversing order of recent messages or results.

Permalink

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)

Follow:

Example:

List<int> list = new List<int>();

list.Add(10); // Type-safe

ArrayList arrayList = new ArrayList();

arrayList.Add(10);

int num = (int)arrayList[0]; // Casting required

Best Practice:

Always prefer List<T> in new code. Use ArrayList only when working with legacy

systems.

Permalink

C# Collections C# Programming Tutorial · Collections

  • For reference types, null keys are not allowed — adding one throws an

ArgumentNullException.

  • For value types, keys must be non-nullable (like int, Guid).

This restriction ensures the integrity of hashing, which is used internally by the dictionary.

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Clear() method to remove all elements.

Example:

list.Clear();

Permalink

C# Collections C# Programming Tutorial · Collections

You can iterate using:

Permalink

C# Collections C# Programming Tutorial · Collections

KeyValuePair<TKey, TValue> represents a single item in a dictionary — a key-value

pair.

Used in:

  • Iteration
  • LINQ queries
  • Return values from dictionary enumerators

Example:

foreach (KeyValuePair<string, int> entry in dictionary)

Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");

Permalink

C# Collections C# Programming Tutorial · Collections

Method Returns

Find() First match

FindAll

All matches in a new list

Example:

var firstEven = list.Find(x => x % 2 == 0);

var allEvens = list.FindAll(x => x % 2 == 0);

Permalink

C# Collections C# Programming Tutorial · Collections

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 &

Permalink

C# Collections C# Programming Tutorial · Collections

Contains(item) checks whether the item exists in the list. It uses Equals() internally.

Example:

Follow:

bool exists = list.Contains(10);

Note: For custom objects, override Equals() and GetHashCode().

Permalink

C# Collections C# Programming Tutorial · Collections

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

Permalink

C# Collections C# Programming Tutorial · Collections

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}");

Permalink

C# Collections C# Programming Tutorial · Collections

Use GroupBy, Distinct, or nested loops.

Follow:

Example:

bool hasDuplicates = list.Count != list.Distinct().Count();

Permalink

C# Collections C# Programming Tutorial · Collections

Use ToArray() method.

Example:

int[] array = list.ToArray();

Useful when interfacing with APIs that require arrays.

Permalink

C# Collections C# Programming Tutorial · Collections

list = list.Distinct().ToList();

For custom objects, override Equals() and GetHashCode().

Permalink

C# Collections C# Programming Tutorial · Collections

Use IndexOf(item) or FindIndex(predicate).

Example:

int index = list.IndexOf(10);

int indexByCondition = list.FindIndex(x => x > 100);

Follow:

📘 C# Dictionary<TKey, TValue> –

Interview Questions & Answers

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

  • 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.
Permalink

C# OOP C# Programming Tutorial · OOP

functionality.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

class Vehicle {} // Base

class Car : Vehicle {} // Single/Multilevel

class Bike : Vehicle {} // Hierarchical

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

  • 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.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

overloading/overriding).

Permalink

C# OOP C# Programming Tutorial · OOP

  • Encourages modular code → easier to maintain and test.
  • Reduces code duplication through inheritance and composition.
  • Improves scalability and flexibility in large projects.
  • Enhances team collaboration as objects represent real-world entities.
Permalink

C# OOP C# Programming Tutorial · OOP

  • 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"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • An instance of a class with actual values.
  • Represents a real-world entity in memory.

Car myCar = new Car(); // Object of Car class

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Class Object

Definition Blueprint/Template Instance of a class

Memory Does not occupy

memory

Occupies memory

Example class Car { } Car myCar = new

Car();

Permalink

C# OOP C# Programming Tutorial · OOP

  • 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");

Permalink

C# OOP C# Programming Tutorial · OOP

  • A method called automatically when an object is destroyed.
  • Used to release resources before the object is removed from memory.
  • In C#, destructors are rarely needed due to garbage collection.

~Car() { Console.WriteLine("Car object destroyed"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • 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

Permalink

C# OOP C# Programming Tutorial · OOP

  • 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; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Hiding implementation details and showing only the essential features of an

object.

  • Achieved using abstract classes and interfaces.

abstract class Vehicle

public abstract void Start();

Permalink

C# OOP C# Programming Tutorial · OOP

  • 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

Permalink

C# OOP C# Programming Tutorial · OOP

  • 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

action.

🔹 Section 2: Encapsulation – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Encapsulation is the mechanism of hiding internal details of an object and

exposing only necessary functionalities.

  • It helps in protecting data and maintaining control over how it is accessed or

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 +=

amount; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • By making fields private, external code cannot directly modify sensitive data.
  • Access is controlled via methods or properties, enforcing validation rules.

Example: Prevent withdrawing more than the account balance:

public void Withdraw(decimal amount)

if (amount <= balance) balance -= amount;

else throw new InvalidOperationException("Insufficient

balance");

Permalink

C# OOP C# Programming Tutorial · OOP

  • Use private fields to store data.
  • Expose controlled access via public properties or methods.
  • Apply validation logic inside these methods/properties.

private int age;

public int Age

get { return age; }

set { if (value > 0) age = value; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Keywords that define visibility of class members.
  • Common C# modifiers:
  • private → accessible only inside the class
  • public → accessible from anywhere
  • protected → accessible in class and derived classes
  • internal → accessible within the same assembly
  • protected internal → accessible in derived classes or same assembly
Permalink

C# OOP C# Programming Tutorial · OOP

  • Private → Hides data from outside access, ensuring security.
  • Public → Provides controlled access through properties or methods.

Example:

private decimal balance; // hidden

public decimal Balance { get { return balance; } } // read-only

access

Permalink

C# OOP C# Programming Tutorial · OOP

  • Internal → Accessible only within the same assembly.
  • Protected → Accessible in the class and derived classes.
  • Protected Internal → Accessible in derived classes or within the same assembly.

Example:

protected string accountType; // accessible in derived classes

internal string branchCode; // accessible within same assembly

Permalink

C# OOP C# Programming Tutorial · OOP

  • Technically yes, but not recommended.
  • Makes the data vulnerable to invalid modifications.
  • Encapsulation recommends private fields + public properties.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Properties provide controlled access to private fields.
  • Enable validation, read-only/write-only access, and future flexibility.

Example:

private int score;

public int Score

get { return score; }

set { if (value >= 0) score = value; } // validation

Permalink

C# OOP C# Programming Tutorial · OOP

  • Encapsulation → Hides internal data, focuses on data protection.
  • Abstraction → Hides implementation details, focuses on simplifying complex

systems.

Permalink

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)

accountNumber = accNum;

balance = initialBalance >= 0 ? initialBalance : throw new

ArgumentException("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:

  • accountNumber and balance are private, protecting sensitive data.
  • Controlled access via methods ensures data integrity.
  • Demonstrates real-world encapsulation in action.

🔹 Section 3: Abstraction – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Abstraction is the process of hiding the internal implementation details of a

system and exposing only the essential features.

  • It allows developers to focus on what an object does, not how it does it.

Example: A Vehicle class exposes Start() method without revealing engine details.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Simplifies complex systems by exposing only relevant functionality.
  • Enhances maintainability, readability, and reusability of code.
  • Reduces dependency on implementation details, making systems more flexible.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Using abstract classes or interfaces.
  • Abstract classes can have abstract and non-abstract methods.
  • Interfaces define method signatures only.

abstract class Vehicle

public abstract void Start();

interface IDriveable

void Drive();

Permalink

C# OOP C# Programming Tutorial · OOP

  • Classes that cannot be instantiated directly and may contain abstract methods

(without implementation).

  • Can have fields, constructors, and concrete methods.

abstract class Animal

public abstract void MakeSound();

public void Sleep() => Console.WriteLine("Sleeping");

Permalink

C# OOP C# Programming Tutorial · OOP

  • 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();

Permalink

C# OOP C# Programming Tutorial · OOP

  • By exposing method signatures only, interfaces hide the implementation.
  • Allows multiple classes to implement the interface differently, providing flexibility

and decoupling.

class Bird : IFlyable

public void Fly() => Console.WriteLine("Bird is flying");

class Airplane : IFlyable

public void Fly() => Console.WriteLine("Airplane is flying");

Permalink

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

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, abstract classes cannot be instantiated directly.
  • Must be inherited by a derived class which implements abstract methods.

abstract class Shape { public abstract void Draw(); }

// Shape s = new Shape(); // Not allowed

class Circle : Shape { public override void Draw() =>

Console.WriteLine("Circle"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, abstract classes can have concrete methods with implementation.
  • Allows shared behavior for derived classes.

abstract class Animal

public void Sleep() => Console.WriteLine("Sleeping");

public abstract void MakeSound();

Permalink

C# OOP C# Programming Tutorial · OOP

  • Reduces system complexity by focusing on essential features.
  • Decouples modules, making large systems easier to maintain and extend.
  • Promotes code reuse and flexibility.
Permalink

C# OOP C# Programming Tutorial · OOP

  • 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.
Permalink

C# OOP C# Programming Tutorial · OOP

Real-World Example: Payment Processing

// Abstract class

abstract 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:

  • Payment defines what a payment should do (abstract method Pay).
  • Derived classes (CreditCardPayment, PayPalPayment) define how payment is

made.

  • Users interact only with the abstract interface, not the internal logic.

🔹 Section 4: Inheritance – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Inheritance is an OOP mechanism where a class (derived/child) inherits

properties and methods from another class (base/parent).

  • Promotes code reusability and hierarchical relationships.

class Vehicle { public void Start() => Console.WriteLine("Vehicle

started"); }

class Car : Vehicle { } // Car inherits from Vehicle

Permalink

C# OOP C# Programming Tutorial · OOP

  • 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

Permalink

C# OOP C# Programming Tutorial · OOP

  • Using the colon (:) symbol.
  • Derived class can access public/protected members of the base class.

class Vehicle { public void Start() => Console.WriteLine("Start"); }

class Car : Vehicle { }

Car myCar = new Car();

myCar.Start(); // Inherited method

Permalink

C# OOP C# Programming Tutorial · OOP

  • Calls the constructor of the base class from a derived class.
  • Ensures base class initialization before derived class constructor runs.

class Vehicle { public Vehicle(string brand) {

Console.WriteLine(brand); } }

class Car : Vehicle

public Car(string brand) : base(brand) { Console.WriteLine("Car

created"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, C# does not support multiple class inheritance to avoid ambiguity.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Use interfaces to achieve multiple inheritance.
  • A class can implement multiple interfaces.

interface IFlyable { void Fly(); }

interface IDriveable { void Drive(); }

class FlyingCar : IFlyable, IDriveable { public void Fly() {} public

void Drive() {} }

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Inheritance Composition

Relationship "is-a" "has-a"

Reuse Derived class reuses base

class

Object contains other

objects

Flexibility Less flexible More flexible

Example:

  • Inheritance → Car is a Vehicle
  • Composition → Car has a Engine
Permalink

C# OOP C# Programming Tutorial · OOP

  • virtual → Marks a base class method as overridable.
  • override → Overrides a virtual method in the derived class.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Prevents a class from being inherited or a method from being overridden.

sealed class FinalClass { }

class Car : FinalClass { } // Not allowed

Permalink

C# OOP C# Programming Tutorial · OOP

  • override → Overrides a virtual method in base class (runtime polymorphism).
  • new → Hides a base class method (compile-time hiding, not true overriding).

class Vehicle { public void Start() => Console.WriteLine("Vehicle");

class Car : Vehicle { public new void Start() =>

Console.WriteLine("Car"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Common functionality is implemented in base class.
  • Derived classes reuse the code without duplicating it, reducing maintenance effort.
Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Base class constructor executes first, then derived class constructor.
  • Ensures base members are initialized before derived members.
Permalink

C# OOP C# Programming Tutorial · OOP

  • No, private members are hidden from derived classes.
  • Can access protected, internal, or public members.

class Vehicle { private int id; protected string model; }

class Car : Vehicle { /* cannot access id, can access model */ }

🔹 Section 5: Polymorphism – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Polymorphism means “many forms”.
  • It allows objects of different types to be treated as objects of a common base

type.

  • Achieved through method overloading, overriding, and interfaces.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Also called static polymorphism.
  • Resolved at compile time.
  • Achieved through method overloading or operator overloading.

class Calculator

public int Add(int a, int b) => a + b;

public double Add(double a, double b) => a + b; // Overloaded

method

Permalink

C# OOP C# Programming Tutorial · OOP

  • Also called dynamic polymorphism.
  • Resolved at runtime using method overriding.

class Vehicle { public virtual void Start() =>

Console.WriteLine("Vehicle starts"); }

class Car : Vehicle { public override void Start() =>

Console.WriteLine("Car starts"); }

Vehicle v = new Car();

v.Start(); // Calls Car's Start() at runtime

Permalink

C# OOP C# Programming Tutorial · OOP

  • Same method name with different parameters in the same class.
  • Enables compile-time polymorphism.

class MathHelper

public int Multiply(int a, int b) => a * b;

public int Multiply(int a, int b, int c) => a * b * c; //

Overloaded

Permalink

C# OOP C# Programming Tutorial · OOP

  • Derived class provides a new implementation for a virtual method in base class.
  • Enables runtime polymorphism.

class Vehicle { public virtual void Start() =>

Console.WriteLine("Vehicle starts"); }

class Car : Vehicle { public override void Start() =>

Console.WriteLine("Car starts"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, constructors can have multiple signatures in the same class.

class Car

public Car() { }

public Car(string model) { }

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, constructors cannot be inherited or overridden.
  • Base class constructor can be called using : base(), but cannot be overridden.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Defining custom behavior for operators (+, -, *, etc.) for a class.

class Point

public int X, Y;

public static Point operator +(Point a, Point b) => new Point {

X = a.X + b.X, Y = a.Y + b.Y };

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Overloading Overriding

Compile/Runtime Compile-time Runtime

Same signature? No, different parameters Same

signature

Virtual required? No Yes

Inheritance

required?

Not required Required

Permalink

C# OOP C# Programming Tutorial · OOP

  • Early binding → Resolved at compile time (e.g., method overloading).
  • Late binding → Resolved at runtime (e.g., method overriding with virtual/override).
Permalink

C# OOP C# Programming Tutorial · OOP

  • object is the base class for all C# types.
  • Enables polymorphism, as any object can be referred using object type.

object obj = new Car();

Permalink

C# OOP C# Programming Tutorial · OOP

  • Through:
Permalink

C# OOP C# Programming Tutorial · OOP

abstract class Shape { public abstract void Draw(); }

class Circle : Shape { public override void Draw() =>

Console.WriteLine("Drawing Circle"); }

class Rectangle : Shape { public override void Draw() =>

Console.WriteLine("Drawing Rectangle"); }

Shape s1 = new Circle();

Shape s2 = new Rectangle();

s1.Draw(); // Circle's Draw

s2.Draw(); // Rectangle's Draw

Permalink

C# OOP C# Programming Tutorial · OOP

  • Interfaces allow different classes to implement the same contract, enabling

dynamic behavior at runtime.

interface IDriveable { void Drive(); }

class Car : IDriveable { public void Drive() =>

Console.WriteLine("Car drives"); }

class Bike : IDriveable { public void Drive() =>

Console.WriteLine("Bike drives"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Another term for runtime polymorphism, achieved via method overriding.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Code depends on interfaces or base classes, not concrete implementations.
  • Makes system flexible, extendable, and easier to maintain.

void StartVehicle(Vehicle v) { v.Start(); } // Works with any

derived type

Permalink

C# OOP C# Programming Tutorial · OOP

Advantages:

  • Promotes code reuse and flexibility
  • Enables loose coupling
  • Supports extensible architecture

Disadvantages:

  • May introduce runtime overhead
  • Can make code harder to understand if overused
  • Requires careful design to avoid ambiguity

🔹 Section 6: Interfaces in C# – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • An interface is a contract that defines method signatures, properties, events, or

indexers without providing implementation.

  • Classes or structs that implement the interface must provide the implementation.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Use the interface keyword.

interface IDriveable

void Drive();

int Speed { get; set; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Use the colon (:) symbol and implement all members.

class Car : IDriveable

public int Speed { get; set; }

public void Drive() => Console.WriteLine("Car is driving");

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, interfaces cannot have fields. Only methods, properties, events, or indexers.
Permalink

C# OOP C# Programming Tutorial · OOP

  • No, interfaces cannot have constructors.
Permalink