Master Data Structures & Algorithms in C#
Your comprehensive guide to implementing efficient data structures and algorithms in C#
Data Structures
Arrays & Lists
Fundamental data structures for storing and accessing elements sequentially.
Key Concepts:
- Array implementation and manipulation
- List
and ArrayList - Dynamic arrays and resizing
- Multi-dimensional arrays
- Jagged arrays
- Array sorting and searching
- Array algorithms (prefix sums, sliding window)
// Array implementation
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
// List implementation
List dynamicList = new List();
dynamicList.Add(1);
dynamicList.Add(2);
// Multi-dimensional array
int[,] matrix = new int[3, 3];
// Jagged array
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[4];
jaggedArray[1] = new int[2];
jaggedArray[2] = new int[3];
Linked Lists
Dynamic data structure for efficient insertions and deletions.
Key Concepts:
- Singly linked lists
- Doubly linked lists
- Circular linked lists
- LinkedList
implementation - Linked list algorithms
- Cycle detection
- Merge sorted lists
- Reverse linked list
// Custom LinkedList Node
public class ListNode {
public int Value { get; set; }
public ListNode Next { get; set; }
public ListNode(int value) {
Value = value;
Next = null;
}
}
// LinkedList implementation
public class LinkedList {
private ListNode head;
public void AddFirst(int value) {
ListNode node = new ListNode(value);
node.Next = head;
head = node;
}
public void AddLast(int value) {
ListNode node = new ListNode(value);
if (head == null) {
head = node;
return;
}
ListNode current = head;
while (current.Next != null) {
current = current.Next;
}
current.Next = node;
}
}
Stacks & Queues
LIFO and FIFO data structures for specific use cases.
Key Concepts:
- Stack
implementation - Queue
implementation - Priority queues
- Deque implementation
- Stack applications
- Queue applications
- Circular queue
- Min/Max stack
// Stack implementation
Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
int top = stack.Pop();
// Queue implementation
Queue queue = new Queue();
queue.Enqueue("First");
queue.Enqueue("Second");
string first = queue.Dequeue();
// Priority Queue
PriorityQueue priorityQueue = new PriorityQueue();
priorityQueue.Enqueue(1, 1);
priorityQueue.Enqueue(2, 0);
int highestPriority = priorityQueue.Dequeue();
Trees & Graphs
Hierarchical and network data structures.
Key Concepts:
- Binary trees
- Binary search trees
- AVL trees
- Red-Black trees
- B-trees
- Graph representations
- Trie data structure
- Segment trees
// Binary Tree Node
public class TreeNode {
public int Value { get; set; }
public TreeNode Left { get; set; }
public TreeNode Right { get; set; }
public TreeNode(int value) {
Value = value;
Left = Right = null;
}
}
// Graph representation
public class Graph {
private Dictionary> adjacencyList;
public Graph() {
adjacencyList = new Dictionary>();
}
public void AddEdge(int source, int destination) {
if (!adjacencyList.ContainsKey(source)) {
adjacencyList[source] = new List();
}
adjacencyList[source].Add(destination);
}
}
Hash Tables & Sets
Efficient data structures for lookups and unique elements.
Key Concepts:
- Dictionary
- HashSet
- Hash function implementation
- Collision resolution
- Load factor and rehashing
- Custom hash tables
- Bloom filters
// Dictionary implementation
Dictionary dict = new Dictionary();
dict["one"] = 1;
dict["two"] = 2;
// HashSet implementation
HashSet set = new HashSet();
set.Add(1);
set.Add(2);
// Custom HashTable
public class CustomHashTable {
private class Entry {
public TKey Key { get; set; }
public TValue Value { get; set; }
public bool IsDeleted { get; set; }
}
private Entry[] buckets;
private int count;
public CustomHashTable(int capacity = 16) {
buckets = new Entry[capacity];
}
}
Advanced Data Structures
Specialized data structures for specific use cases.
Key Concepts:
- Skip lists
- Disjoint-set (Union-Find)
- Fenwick trees
- Binary indexed trees
- Suffix trees
- B+ trees
- Quad trees
- R-trees
// Disjoint Set implementation
public class DisjointSet {
private int[] parent;
private int[] rank;
public DisjointSet(int size) {
parent = new int[size];
rank = new int[size];
for (int i = 0; i < size; i++) {
parent[i] = i;
rank[i] = 0;
}
}
public int Find(int x) {
if (parent[x] != x) {
parent[x] = Find(parent[x]);
}
return parent[x];
}
public void Union(int x, int y) {
int rootX = Find(x);
int rootY = Find(y);
if (rootX == rootY) return;
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
Algorithms
Sorting Algorithms
Bubble Sort
A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
Complexity:
- Time: O(n²)
- Space: O(1)
public static void BubbleSort(int[] arr)
{
int n = arr.Length;
bool swapped;
for (int i = 0; i < n - 1; i++)
{
swapped = false;
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (swapped == false)
break;
}
}
Selection Sort
A simple sorting algorithm that divides the input list into two parts: a sorted sublist of items which is built up from left to right at the front (left) of the list, and a sublist of the remaining unsorted items that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.
Complexity:
- Time: O(n²)
- Space: O(1)
public static void SelectionSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
int min_idx = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
Insertion Sort
A simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages: Simple implementation, Efficient for small data sets, More efficient in practice than most other simple quadratic algorithms, such as selection sort or bubble sort, Best case is O(n), Adaptive (performs well on data that is already substantially sorted).
Complexity:
- Time: O(n²)
- Space: O(1)
public static void InsertionSort(int[] arr)
{
int n = arr.Length;
for (int i = 1; i < n; ++i)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
Quick Sort
A highly efficient sorting algorithm that works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively.
Complexity:
- Time: Average O(n log n), Worst O(n²)
- Space: O(log n) - O(n) (depending on implementation)
public static void QuickSort(int[] arr, int low, int high)
{
if (low < high)
{
int pi = Partition(arr, low, high);
QuickSort(arr, low, pi - 1);
QuickSort(arr, pi + 1, high);
}
}
private static int Partition(int[] arr, int low, int high)
{
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
if (arr[j] < pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp1 = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp1;
return i + 1;
}
Merge Sort
A divide and conquer algorithm that divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves. The merge function is used to merge two sorted arrays.
Complexity:
- Time: O(n log n)
- Space: O(n)
public static void MergeSort(int[] arr, int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
MergeSort(arr, l, m);
MergeSort(arr, m + 1, r);
Merge(arr, l, m, r);
}
}
private static void Merge(int[] arr, int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int[] L = new int[n1];
int[] R = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int k = l;
int i_l = 0, j_r = 0;
while (i_l < n1 && j_r < n2)
{
if (L[i_l] <= R[j_r])
{
arr[k] = L[i_l];
i_l++;
}
else
{
arr[k] = R[j_r];
j_r++;
}
k++;
}
while (i_l < n1)
{
arr[k] = L[i_l];
i_l++;
k++;
}
while (j_r < n2)
{
arr[k] = R[j_r];
j_r++;
k++;
}
}
Heap Sort
A comparison-based sorting technique based on Binary Heap data structure. It is similar to Selection Sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining elements.
Complexity:
- Time: O(n log n)
- Space: O(1)
public static void HeapSort(int[] arr)
{
int n = arr.Length;
for (int i = n / 2 - 1; i >= 0; i--)
Heapify(arr, n, i);
for (int i = n - 1; i > 0; i--)
{
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
Heapify(arr, i, 0);
}
}
private static void Heapify(int[] arr, int n, int i)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
Heapify(arr, n, largest);
}
}
Counting Sort
A non-comparison based sorting algorithm. It is effective when the difference between the maximum and minimum element in the input array is not significantly greater than the number of elements in the array. It counts the frequency of each element and uses that information to place elements in the sorted array.
Complexity:
- Time: O(n + k) (where k is the range of input)
- Space: O(k)
public static void CountingSort(int[] arr, int max)
{
int n = arr.Length;
int[] output = new int[n];
int[] count = new int[max + 1];
for (int i = 0; i < n; i++)
count[arr[i]]++;
for (int i = 1; i <= max; i++)
count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--)
{
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
Radix Sort
A non-comparative sorting algorithm. It avoids comparison by creating and distributing elements into buckets according to their radix. It is typically implemented using Counting Sort as the stable sorting algorithm for each digit.
Complexity:
- Time: O(nk) (where n is number of elements, k is number of digits)
- Space: O(n + k)
public static void RadixSort(int[] arr)
{
int max = GetMax(arr);
for (int exp = 1; max / exp > 0; exp *= 10)
CountSort(arr, exp);
}
private static int GetMax(int[] arr)
{
int max = arr[0];
for (int i = 1; i < arr.Length; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
private static void CountSort(int[] arr, int exp)
{
int n = arr.Length;
int[] output = new int[n];
int[] count = new int[10];
for (int i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;
for (int i = 1; i < 10; i++)
count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--)
{
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
Bucket Sort
A non-comparison based sorting algorithm that works by distributing elements into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sort algorithm. It is a generalization of pigeonhole sort.
Complexity:
- Time: Average O(n + k), Worst O(n²)
- Space: O(n + k)
public static void BucketSort(float[] arr)
{
int n = arr.Length;
if (n <= 0) return;
List[] buckets = new List[n];
for (int i = 0; i < n; i++) buckets[i] = new List();
for (int i = 0; i < n; i++)
{
int bi = (int)(n * arr[i]);
buckets[bi].Add(arr[i]);
}
for (int i = 0; i < n; i++) buckets[i].Sort();
int index = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < buckets[i].Count; j++)
{
arr[index++] = buckets[i][j];
}
}
}
Searching Algorithms
Linear Search
A simple search algorithm that sequentially checks each element of the list until a match is found or the whole list has been searched.
Complexity:
- Time: O(n)
- Space: O(1)
public static int LinearSearch(int[] arr, int target)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == target) return i;
}
return -1;
}
Binary Search
An efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.
Complexity:
- Time: O(log n)
- Space: O(1) iterative, O(log n) recursive
public static int BinarySearch(int[] arr, int target)
{
int left = 0;
int 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;
}
Depth-First Search (DFS)
An algorithm for traversing or searching tree or graph data structures. It starts at the root (or some arbitrary node of a graph, sometimes referred to as a 'search key') and explores as far as possible along each branch before backtracking.
Complexity:
- Time: O(V + E) (for graphs)
- Space: O(V)
public static void DFS(Graph graph, int start, HashSet visited)
{
visited.Add(start);
// Assuming Graph has a GetNeighbors method
foreach (int neighbor in graph.GetNeighbors(start))
{
if (!visited.Contains(neighbor))
{
DFS(graph, neighbor, visited);
}
}
}
// Example Graph class structure (needs proper implementation)
public class Graph
{
public Dictionary> AdjList { get; set; }
public IEnumerable Vertices => AdjList.Keys;
public Graph()
{
AdjList = new Dictionary>();
}
public void AddEdge(int u, int v)
{
if (!AdjList.ContainsKey(u)) AdjList[u] = new List();
AdjList[u].Add(v);
}
public List GetNeighbors(int u)
{
return AdjList.ContainsKey(u) ? AdjList[u] : new List();
}
}
Breadth-First Search (BFS)
An algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key') and explores the neighbor nodes first, before moving to the next level neighbors.
Complexity:
- Time: O(V + E) (for graphs)
- Space: O(V)
public static void BFS(Graph graph, int start)
{
HashSet visited = new HashSet();
Queue queue = new Queue();
visited.Add(start);
queue.Enqueue(start);
while (queue.Count > 0)
{
int vertex = queue.Dequeue();
// Assuming Graph has a GetNeighbors method
foreach (int neighbor in graph.GetNeighbors(vertex))
{
if (!visited.Contains(neighbor))
{
visited.Add(neighbor);
queue.Enqueue(neighbor);
}
}
}
}
// Example Graph class structure (needs proper implementation)
public class Graph
{
public Dictionary> AdjList { get; set; }
public IEnumerable Vertices => AdjList.Keys;
public Graph()
{
AdjList = new Dictionary>();
}
public void AddEdge(int u, int v)
{
if (!AdjList.ContainsKey(u)) AdjList[u] = new List();
AdjList[u].Add(v);
}
public List GetNeighbors(int u)
{
return AdjList.ContainsKey(u) ? AdjList[u] : new List();
}
}
Graph Algorithms
Dijkstra's Algorithm
An algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later. The algorithm exists in many variants; Dijkstra's original algorithm found the shortest path from a source node to a single target node, but a more common variant finds shortest paths from a source node to all other nodes in the graph, producing a shortest-path tree.
Complexity:
- Time: O((V + E) log V) or O(E log V) with Fibonacci heap
- Space: O(V + E)
// Requires a PriorityQueue implementation
// Example implementation structure (needs full implementation)
public class PriorityQueue {
public void Enqueue(TElement element, TPriority priority) { /* ... */ }
public TElement Dequeue() { /* ... */ }
public int Count { get; }
}
public static Dictionary Dijkstra(WeightedGraph graph, int start)
{
var distances = new Dictionary();
var pq = new PriorityQueue(); // Needs proper PriorityQueue
foreach (var vertex in graph.Vertices)
{
distances[vertex] = int.MaxValue;
}
distances[start] = 0;
pq.Enqueue(start, 0);
while (pq.Count > 0)
{
var current = pq.Dequeue();
// Assuming WeightedGraph has GetNeighbors and GetWeight methods
foreach (var neighbor in graph.GetNeighbors(current))
{
// Assuming edge weights are positive
var distance = distances[current] + graph.GetWeight(current, neighbor);
if (distance < distances[neighbor])
{
distances[neighbor] = distance;
pq.Enqueue(neighbor, distance); // Update priority
}
}
}
return distances;
}
// Example WeightedGraph class structure (needs proper implementation)
public class WeightedGraph
{\n public Dictionary>> AdjList { get; set; }
public IEnumerable Vertices => AdjList.Keys;
public WeightedGraph()
{
AdjList = new Dictionary>>();
}
public void AddEdge(int u, int v, int weight)
{
if (!AdjList.ContainsKey(u)) AdjList[u] = new List>();
AdjList[u].Add(Tuple.Create(v, weight));
}
public List GetNeighbors(int u)
{
// Simplified: returns neighbor nodes, not weight tuples
return AdjList.ContainsKey(u) ? AdjList[u].Select(edge => edge.Item1).ToList() : new List();
}
public int GetWeight(int u, int v)
{
// Simplified: finds weight for a specific edge
if (AdjList.ContainsKey(u))
{
var edge = AdjList[u].FirstOrDefault(e => e.Item1 == v);
if (edge != null) return edge.Item2;
}
return int.MaxValue; // No direct edge
}
}
Kruskal's Algorithm
A greedy algorithm to find a minimum spanning tree for a connected weighted undirected graph. It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.
Complexity:
- Time: O(E log E) or O(E log V)
- Space: O(V + E)
// Requires a Disjoint Set (Union-Find) data structure
// Example DisjointSet class structure (needs proper implementation)
public class DisjointSet
{
private int[] parent;
private int[] rank;
public DisjointSet(int size)
{
parent = new int[size];
rank = new int[size];
for (int i = 0; i < size; i++) parent[i] = i;
}
public int Find(int i)
{
if (parent[i] == i) return i;
return parent[i] = Find(parent[i]);
}
public void Union(int i, int j)
{
int rootI = Find(i);
int rootJ = Find(j);
if (rootI != rootJ)
{
if (rank[rootI] < rank[rootJ])
parent[rootI] = rootJ;
else if (rank[rootI] > rank[rootJ])
parent[rootJ] = rootI;
else
{
parent[rootJ] = rootI;
rank[rootI]++;
}
}
}
}
// Edge class for weighted graph
public class Edge
{\n public int Source, Destination, Weight;
}
public static List Kruskal(List edges, int V)
{
edges.Sort((a, b) => a.Weight.CompareTo(b.Weight)); // Sort edges by weight
DisjointSet ds = new DisjointSet(V);
List result = new List();
int edgeCount = 0;
foreach (var edge in edges)
{
if (edgeCount == V - 1) break;
int rootSource = ds.Find(edge.Source);
int rootDest = ds.Find(edge.Destination);
if (rootSource != rootDest)
{
result.Add(edge);
ds.Union(rootSource, rootDest);
edgeCount++;
}
}
return result;
}
Prim's Algorithm
A greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. It builds the tree by starting from an arbitrary vertex and repeatedly adding the edge with the lowest weight that connects a vertex in the tree to a vertex outside the tree.
Complexity:
- Time: O((V + E) log V) or O(E log V) with Fibonacci heap
- Space: O(V)
// Requires a PriorityQueue implementation
// Example PriorityQueue class structure (needs full implementation)
public class PriorityQueue {
public void Enqueue(TElement element, TPriority priority) { /* ... */ }
public TElement Dequeue() { /* ... */ }
public int Count { get; }
}
public static List Prim(WeightedGraph graph, int startVertex)
{
int V = graph.Vertices.Count();
var minHeap = new PriorityQueue(); // Stores (vertex, key)
var parent = new int[V];
var key = new int[V];
var inMST = new bool[V];
for (int i = 0; i < V; i++)
{
key[i] = int.MaxValue;
inMST[i] = false;
}
minHeap.Enqueue(startVertex, 0); // Add start vertex with key 0
key[startVertex] = 0;
parent[startVertex] = -1; // First node is always root of MST
while (minHeap.Count > 0)
{
int u = minHeap.Dequeue();
inMST[u] = true;
// Assuming WeightedGraph has GetNeighborsWithWeight method returning tuples (neighbor, weight)
foreach (var neighborEdge in graph.GetNeighborsWithWeight(u))
{
int v = neighborEdge.Item1;
int weight = neighborEdge.Item2;
if (inMST[v] == false && weight < key[v])
{
parent[v] = u;
key[v] = weight;
minHeap.Enqueue(v, key[v]);
}
}
}
List mst = new List();
for (int i = 1; i < V; i++)
{
// Need to get weight for edge (parent[i], i) - Requires graph method
// Simplified: just adding edge based on parent link
// mst.Add(new Edge { Source = parent[i], Destination = i, Weight = /* Get weight */ });
}
return mst; // Returns parent array or construct edge list
}
// Add GetNeighborsWithWeight to WeightedGraph class if needed
// public List> GetNeighborsWithWeight(int u) { /* ... */ }
Topological Sort
A linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge uv, vertex u comes before v in the ordering. Topological sorting is possible only for DAGs.
Complexity:
- Time: O(V + E)
- Space: O(V)
public static List TopologicalSort(Graph graph)
{
var result = new List();
var visited = new HashSet();
var recursionStack = new HashSet();
var stack = new Stack();
foreach (var vertex in graph.Vertices)
{
if (!visited.Contains(vertex))
{
if (!TopologicalSortUtil(graph, vertex, visited, recursionStack, stack))
{
// Cycle detected, cannot perform topological sort
return null; // Or throw exception
}
}
}
while (stack.Count > 0)
{
result.Add(stack.Pop());
}
return result;
}
private static bool TopologicalSortUtil(Graph graph, int u, HashSet visited, HashSet recursionStack, Stack stack)
{
visited.Add(u);
recursionStack.Add(u);
foreach (var v in graph.GetNeighbors(u))
{
if (!visited.Contains(v))
{
if (!TopologicalSortUtil(graph, v, visited, recursionStack, stack)) return false;
}
else if (recursionStack.Contains(v))
{
return false; // Cycle detected
}
}
recursionStack.Remove(u);
stack.Push(u);
return true;
}
// Example Graph class structure (needs proper implementation)
// See DFS/BFS for Graph class structure
Bellman-Ford Algorithm
An algorithm that computes shortest paths from a single source vertex to all of the other vertices in a weighted directed graph. It is slower than Dijkstra's algorithm for the same problem, but unlike Dijkstra's algorithm, it can handle graphs in which some of the edge weights are negative. The algorithm detects negative cycles.
Complexity:
- Time: O(V * E)
- Space: O(V)
// Requires a representation of edges with weights
// Example Edge class (see Kruskal's)
// public class Edge { public int Source, Destination, Weight; }
public static Dictionary BellmanFord(List edges, int V, int source)
{
var distance = new Dictionary();
for (int i = 0; i < V; i++) distance[i] = int.MaxValue;
distance[source] = 0;
// Relax edges V-1 times
for (int i = 0; i < V - 1; i++)
{
foreach (var edge in edges)
{
if (distance[edge.Source] != int.MaxValue && distance[edge.Source] + edge.Weight < distance[edge.Destination])
{
distance[edge.Destination] = distance[edge.Source] + edge.Weight;
}
}
}
// Check for negative cycles
foreach (var edge in edges)
{
if (distance[edge.Source] != int.MaxValue && distance[edge.Source] + edge.Weight < distance[edge.Destination])
{
// Graph contains negative weight cycle
return null; // Indicate negative cycle
}
}
return distance;
}
Floyd-Warshall Algorithm
An algorithm for finding shortest paths in a directed weighted graph with positive or negative edge weights (but no negative cycles). It computes shortest paths between all pairs of vertices.
Complexity:
- Time: O(V³)
- Space: O(V²)
// Requires an adjacency matrix representation of the graph
// Assumes graph[i,j] is weight of edge from i to j, or infinity if no edge
// Assumes graph[i,i] is 0
public static int[,] FloydWarshall(int[,] graph, int V)
{
int[,] dist = (int[,])graph.Clone(); // Copy the graph matrix
for (int k = 0; k < V; k++)
{
// Pick all vertices as source one by one
for (int i = 0; i < V; i++)
{
// Pick all vertices as destination for the above picked source
for (int j = 0; j < V; j++)
{
// If vertex k is on the shortest path from i to j, then update the value of dist[i][j]
if (dist[i, k] != int.MaxValue && dist[k, j] != int.MaxValue && dist[i, k] + dist[k, j] < dist[i, j])
{
dist[i, j] = dist[i, k] + dist[k, j];
}
}
}
}
// Optional: Check for negative cycles
for (int i = 0; i < V; i++)
{
if (dist[i, i] < 0)
{
// Negative cycle detected
// Handle as needed (e.g., return null or throw exception)
}
}
return dist;
}
Dynamic Programming
Fibonacci Sequence
A sequence in which each number is the sum of the two preceding ones, usually starting with 0 and 1. Dynamic programming can be used to compute Fibonacci numbers efficiently by storing previously calculated values to avoid redundant computations.
Complexity:
- Time: O(n) (using DP)
- Space: O(n) (for memoization) or O(1) (iterative)
// Using memoization
public class Fibonacci
{
private Dictionary memo = new Dictionary();
public int GetFib(int n)
{
if (n <= 1) return n;
if (memo.ContainsKey(n)) return memo[n];
int result = GetFib(n - 1) + GetFib(n - 2);
memo[n] = result;
return result;
}
}
// Iterative approach (O(1) space)
public static int GetFibIterative(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;
}
Longest Common Subsequence
Finding the longest subsequence common to all sequences in a set of sequences (often just two sequences). A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Complexity:
- Time: O(mn) (where m and n are lengths of sequences)
- Space: O(mn)
public static int LCS(string s1, string s2)
{
int m = s1.Length;
int n = s2.Length;
int[,] dp = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0) dp[i, j] = 0;
else 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];
}
Matrix Chain Multiplication
The problem of determining the most efficient way to multiply a given sequence of matrices. The problem is not actually to perform the multiplications, but merely to decide the order in which to perform the multiplications. Dynamic programming can be used to find the optimal parenthesization.
Complexity:
- Time: O(n³)
- Space: O(n²)
public static int MatrixChainOrder(int[] p)
{
int n = p.Length - 1; // Number of matrices
int[,] m = new int[n, n]; // m[i,j] = minimum scalar multiplications needed to compute A_i...A_j
for (int i = 0; i < n; i++) m[i, i] = 0; // Cost is 0 for single matrix
for (int l = 2; l <= n; l++) // l is chain length
{
for (int i = 0; i < n - l + 1; i++)
{
int j = i + l - 1;
m[i, j] = int.MaxValue;
for (int k = i; k < j; k++)
{
int cost = m[i, k] + m[k + 1, j] + p[i] * p[k + 1] * p[j + 1];
if (cost < m[i, j])
{
m[i, j] = cost;
}
}
}
}
return m[0, n - 1];
}
0/1 Knapsack Problem
Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. Each item can only be taken once (0/1 property).
Complexity:
- Time: O(nW) (where n is number of items, W is knapsack capacity)
- Space: O(nW) or O(W) with optimization
public static int Knapsack(int W, int[] wt, int[] val, int n)
{
int[,] dp = new int[n + 1, W + 1];
for (int i = 0; i <= n; i++)
{
for (int w = 0; w <= W; w++)
{
if (i == 0 || w == 0) dp[i, w] = 0;
else if (wt[i - 1] <= w) dp[i, w] = Math.Max(val[i - 1] + dp[i - 1, w - wt[i - 1]], dp[i - 1, w]);
else dp[i, w] = dp[i - 1, w];
}
}
return dp[n, W];
}
Longest Increasing Subsequence
Given a sequence, find the length of the longest subsequence of the given sequence such that all elements of the subsequence are sorted in increasing order.
Complexity:
- Time: O(n²) or O(n log n) with binary search
- Space: O(n)
// O(n^2) DP approach
public static int LIS(int[] arr)
{
int n = arr.Length;
int[] dp = new int[n]; // dp[i] = length of LIS ending at index i
for (int i = 0; i < n; i++) dp[i] = 1;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (arr[i] > arr[j] && dp[i] < dp[j] + 1)
{
dp[i] = dp[j] + 1;
}
}
}
int max_len = 0;
for (int i = 0; i < n; i++) max_len = Math.Max(max_len, dp[i]);
return max_len;
}
// O(n log n) approach using patience sorting / binary search
// Requires a helper function to find the correct position using binary search
// Simplified for brevity
Edit Distance
The minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other. It is also known as the Levenshtein distance.
Complexity:
- Time: O(mn)
- Space: O(mn) or O(min(m, n)) with optimization
public static int EditDistance(string word1, string word2)
{
int m = word1.Length;
int n = word2.Length;
int[,] dp = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0) dp[i, j] = j;
else if (j == 0) dp[i, j] = i;
else if (word1[i - 1] == word2[j - 1]) dp[i, j] = dp[i - 1, j - 1];
else dp[i, j] = 1 + Math.Min(dp[i, j - 1], // Insert
Math.Min(dp[i - 1, j], // Remove
dp[i - 1, j - 1])); // Replace
}
}
return dp[m, n];
}
Coin Change Problem
Given a set of coin denominations and a target amount, find the minimum number of coins required to make the target amount, or the number of ways to make the target amount using the given denominations. This is a classic dynamic programming problem.
Complexity:
- Time: O(amount * number of denominations)
- Space: O(amount)
// Minimum coins approach
public static int MinCoins(int[] coins, int amount)
{
int[] dp = new int[amount + 1];
Array.Fill(dp, int.MaxValue);
dp[0] = 0;
for (int i = 1; i <= amount; i++)
{
foreach (int coin in coins)
{
if (coin <= i && dp[i - coin] != int.MaxValue)
{
dp[i] = Math.Min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] == int.MaxValue ? -1 : dp[amount];
}
// Number of ways approach
public static int NumberOfWays(int[] coins, int amount)
{
int[] dp = new int[amount + 1];
dp[0] = 1;
foreach (int coin in coins)
{
for (int i = coin; i <= amount; i++)
{
dp[i] += dp[i - coin];
}
}
return dp[amount];
}
Rod Cutting Problem
Given a rod of length n and a table of prices for pieces of size i, find the maximum revenue obtainable by cutting up the rod and selling the pieces.
Complexity:
- Time: O(n²)
- Space: O(n)
public static int CutRod(int[] price, int n)
{
int[] dp = new int[n + 1];
dp[0] = 0;
for (int i = 1; i <= n; i++)
{
int max_val = int.MinValue;
for (int j = 0; j < i; j++)
{
max_val = Math.Max(max_val, price[j] + dp[i - j - 1]);
}
dp[i] = max_val;
}
return dp[n];
}
Complexity Analysis
Time Complexity
- O(1) - Constant time
- O(log n) - Logarithmic time
- O(n) - Linear time
- O(n log n) - Linearithmic time
- O(n²) - Quadratic time
- O(2ⁿ) - Exponential time
- O(n!) - Factorial time
// O(1) - Constant time
int GetFirstElement(int[] arr) {
return arr[0];
}
// O(log n) - Logarithmic time
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;
}
// O(n) - Linear time
int SumArray(int[] arr) {
int sum = 0;
foreach (int num in arr) {
sum += num;
}
return sum;
}
Space Complexity
- In-place algorithms
- Auxiliary space
- Memory management
- Stack space
- Recursive space
- Dynamic allocation
// O(1) - Constant space
void Swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// O(n) - Linear space
int[] CreateArray(int size) {
return new int[size];
}
// O(n) - Recursive space
int Fibonacci(int n) {
if (n <= 1) return n;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
Algorithm Analysis
- Best case analysis
- Worst case analysis
- Average case analysis
- Amortized analysis
- Asymptotic notation
- Big O notation
- Omega notation
- Theta notation
// Best case: O(1)
// Worst case: O(n)
// Average case: O(n)
bool LinearSearch(int[] arr, int target) {
for (int i = 0; i < arr.Length; i++) {
if (arr[i] == target) return true;
}
return false;
}
// Best case: O(log n)
// Worst case: O(log n)
// Average case: O(log n)
bool 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 true;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return false;
}
Learning Resources
Books
-
Introduction to Algorithms
Comprehensive guide to algorithms and their analysis by Thomas H. Cormen.
-
C# Data Structures and Algorithms
Practical implementation guide for C# developers by Marcin Jamro.
-
Algorithms
In-depth coverage of algorithms by Robert Sedgewick and Kevin Wayne.
-
Clean Code
Best practices for writing clean and maintainable code by Robert C. Martin.
Video Courses
-
Data Structures and Algorithms in C#
Complete course with practical examples and implementations.
-
Advanced C# Programming
Deep dive into efficient algorithms and data structures.
-
System Design for Developers
Learn how to design scalable systems using data structures.
-
Competitive Programming
Master algorithms for coding competitions and interviews.
Online Resources
-
Microsoft Documentation
Official C# collections and algorithms guide.
-
LeetCode
Practice problems and solutions for algorithms.
-
GeeksforGeeks
Comprehensive tutorials on data structures and algorithms.
-
HackerRank
Interactive coding challenges and tutorials.