Data structures: which one when?

A one-page cheat sheet: what each basic data structure is good at, what it costs, and the C# type to use.

Data structures: which one when?

Pick a data structure by asking: what will I do most often? Read by position? Look up by key? Add and remove at the ends? Keep things sorted?

Need Use C# type Main cost
Read by position, loop over all Array / list int[], List<T> index O(1), middle insert O(n)
Look up by key, count, remove duplicates Hash table Dictionary<K,V>, HashSet<T> O(1) on average
Last in, first out (undo, brackets, DFS) Stack Stack<T> push amortized O(1), pop O(1)
First in, first out (BFS, jobs) Queue Queue<T> enqueue amortized O(1), dequeue O(1)
Always take the smallest (top k, Dijkstra) Heap PriorityQueue<T,P> O(log n)
Keep sorted while changing, ranges Balanced tree SortedSet<T>, SortedDictionary<K,V> O(log n)
Many inserts/removes at known nodes Linked list LinkedList<T> O(1) at a node, O(n) to find it
Grid data Matrix int[,] O(rows × cols) to visit all
Nested data Tree your own node class depends on shape

How to answer in an interview

  1. Say what operation the problem needs most.
  2. Pick the structure that makes that operation cheap.
  3. Say the cost out loud, and the trade-off: a hash table is fast but unordered; a sorted set is ordered but O(log n).

A quick example

“Find if any two numbers sum to 10” needs fast “have I seen x?” checks, so a HashSet<int> turns it into one pass:

int[] nums = { 3, 9, 7, 1 };
var seen = new HashSet<int>();
bool found = false;
foreach (int x in nums)
{
    found |= seen.Contains(10 - x);
    seen.Add(x);
}
Console.WriteLine(found);

It prints True (3 + 7 = 10).

Read more: https://roadmap.sh/datastructures-and-algorithms

#tip · TIP-032


Write a comment