Data Structures & Algorithms for C# Interviews
Essential data structures and algorithms with C# implementations for technical interviews.
Arrays and Strings
Common Patterns
- Two Pointers
- Sliding Window
- Hash Maps
// Two Sum Problem
public int[] TwoSum(int[] nums, int target)
{
var map = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
int complement = target - nums[i];
if (map.ContainsKey(complement))
return new[] { map[complement], i };
map[nums[i]] = i;
}
return Array.Empty<int>();
}
Lists and LinkedLists
Singly Linked List
public class ListNode
{
public int Val { get; set; }
public ListNode Next { get; set; }
}
// Reverse Linked List
public ListNode ReverseList(ListNode head)
{
ListNode prev = null;
ListNode current = head;
while (current != null)
{
ListNode next = current.Next;
current.Next = prev;
prev = current;
current = next;
}
return prev;
}
Trees and Graphs
Binary Tree Traversal
public class TreeNode
{
public int Val { get; set; }
public TreeNode Left { get; set; }
public TreeNode Right { get; set; }
}
// Inorder Traversal (Recursive)
public void InorderTraversal(TreeNode root, List<int> result)
{
if (root == null) return;
InorderTraversal(root.Left, result);
result.Add(root.Val);
InorderTraversal(root.Right, result);
}
Sorting and Searching
Quick Sort
Time: O(n log n) average, O(n²) worst Space: O(log n)
Binary Search
public int BinarySearch(int[] arr, int target)
{
int left = 0, right = arr.Length - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
Dynamic Programming
Fibonacci (Memoization)
private Dictionary<int, long> memo = new();
public long Fibonacci(int n)
{
if (n <= 1) return n;
if (memo.ContainsKey(n)) return memo[n];
memo[n] = Fibonacci(n - 1) + Fibonacci(n - 2);
return memo[n];
}
Big O Notation
| Complexity | Name | Example |
|---|---|---|
| O(1) | Constant | Array access |
| O(log n) | Logarithmic | Binary search |
| O(n) | Linear | Linear search |
| O(n log n) | Linearithmic | Merge sort |
| O(n²) | Quadratic | Bubble sort |
| O(2āæ) | Exponential | Recursive Fibonacci |