Every standard library ships the same handful of structures under different names: a dynamic array, a hash map and set, a double-ended queue, a sorted tree and a heap. Picking the right one is mostly about asking which operations your code performs most. This lesson gives the questions, the cost table and the per-language names, and explains why the dynamic array is the default.
~35 minBeginnerC# · Python · Java · C++
Curriculum: M04 Built-in Collections · 3 of 3 lessons available
You will be able to
Choose a collection from the operations a task performs: by position, by key, membership, at the ends, in order, or by priority.
Map each abstract structure to its type in C#, Python, Java and C++, including the ones a language does not have.
Quote the cost of the main operations of each structure, with the case (worst, expected, amortized).
Explain why an array-backed list beats a linked list for most workloads despite equal O-notation.
Avoid the classic slow choices: removing from the front of a list, linear membership tests, legacy types.
Helpful before this lesson
M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.
M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
Guidance only. Those modules are planned; the essentials are recapped here.
Visual walkthrough
The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.
The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.
Start from the operations
Choosing a collection is choosing which operations will be cheap. Before naming a type, list what
your code does most often:
Access by position? "Give me element i", "append at the end". → a dynamic array.
Look up by key? "What is the price of item 42?" → a hash map.
Ask "have I seen x?" → a hash set.
Add or remove at the ends? A queue (FIFO) or a stack (LIFO) → a deque or a dynamic array.
Need the elements in sorted order, or the nearest key to x? → a sorted (tree-based) map or
set.
Repeatedly take the smallest or largest? → a priority queue (heap).
Then check the secondary requirements: duplicates, iteration order, memory, and whether references
to elements must stay valid while the collection changes.
The cost table
Costs below are for the standard implementations. "Expected" assumes a reasonable hash function;
"amortized" is over a sequence of operations (see the
best, worst, average and amortized lesson).
Structure
By index
Search by value
Insert / remove at end
At front
In the middle
Ordered iteration
Dynamic array
O(1)
O(n)
amortized O(1) / O(1)
O(n)
O(n)
insertion order
Deque (ring buffer or blocks)
depends on the type (below)
O(n)
amortized O(1)
amortized O(1)
O(n)
insertion order
Linked list (doubly linked)
O(n)
O(n)
O(1)
O(1)
O(1) given a node, O(n) to find it
insertion order
Hash map / set
—
expected O(1) by key
expected O(1)
—
—
unspecified (Python dict: insertion)
Sorted map / set (balanced tree)
—
O(log n) by key
O(log n)
—
—
sorted
Binary heap
—
O(n)
push / pop-min O(log n), peek O(1)
—
—
none
Indexing a deque differs by language: std::deque (C++) is O(1) everywhere; Python's
collections.deque is O(1) at both ends and O(n) toward the middle; C#'s Queue<T> and Java's
ArrayDeque offer no index access at all.
Each linked name opens the collections encyclopedia
page for that type, with every operation's cost, errors, memory effects and a tested example. The
collections cheatsheet puts the same
table on one page. Sorted collections are covered in the third lesson of this module.
Why the dynamic array is the default
The table makes a linked list look attractive: O(1) insertion anywhere. Two catches:
"Given a node." To insert at position i you first have to reach it, which is O(n). The O(1)
only helps when you already hold a reference to the node, as an LRU cache does.
Memory layout. A dynamic array stores elements side by side; a linked list scatters nodes
across the heap, each with one or two pointers of overhead. The lab above traverses both through a
small teaching cache: the array loads a few cache lines and reuses each one for several elements;
the list may need a new line for almost every node. Try the One-line cache preset.
Both traversals are Θ(n), and on real hardware the contiguous one is usually several times faster.
That is why every language's general-purpose list is array-backed, and why the C++ Core Guidelines
and most performance advice say to start with std::vector. Prefer a linked structure only when
you measured a need for it, or when you need stable references to elements while others are
inserted or removed. The dynamic array vs linked list comparison
goes through the trade-off operation by operation.
Language notes
C#. There is no built-in deque; Queue<T> is a FIFO ring buffer and Stack<T> an array
stack. LinkedList<T> is doubly linked and works as a deque at the cost of one node allocation per
element. Dictionary enumeration order is not guaranteed; use OrderedDictionary<TKey,TValue>
(.NET 9+) or a list of keys if order matters.
Python.list.pop(0) and list.insert(0, x) shift every element: O(n). Use
collections.deque for a queue; its append, appendleft, pop and popleft are O(1), but
indexing in the middle is O(n). dict preserves insertion order as a language guarantee since
Python 3.7; set does not. The standard library has no sorted map or set: use bisect on a sorted
list (O(log n) search, O(n) insertion) or a third-party package.
Java.Stack and Vector are legacy, synchronized classes; the Stack documentation itself
recommends Deque implementations instead. ArrayDeque is the default for both stacks and queues
(it rejects null elements). LinkedList implements both List and Deque, but get(i) walks
the list.
C++.std::stack, std::queue and std::priority_queue are adaptors over another container.
std::deque gives O(1) indexing and O(1) insertion at both ends, and does not move existing
elements when it grows at the ends (references stay valid, iterators do not).
std::unordered_map::operator[] inserts a default value when the key is missing; use find or
contains (C++20) to only look.
Common mistakes
Using a list for membership tests in a loop: x in items / Contains is O(n), so a loop of
them is O(n²). Build a set once.
Using a list as a queue by removing from the front.
Choosing a linked list for "fast insertion" when the code finds the position by walking from
the head anyway.
Relying on hash map iteration order, except in Python where dict order is guaranteed.
Forgetting the default direction of std::priority_queue (max) when every other language's is
min.
Reaching for a sorted collection when you only need the minimum (a heap is simpler and faster)
or only need sorted output once (sort at the end).
Worked practice
1. Count how often each word occurs in a large text, then print the counts in any order. Which collection?
A hash map from word to count: Dictionary<string,int>, dict (or collections.Counter),
HashMap<String,Integer> (merge(word, 1, Integer::sum)), std::unordered_map<std::string,int>.
n expected-O(1) updates.
2. Same, but print the words in alphabetical order.
Either count in a hash map and sort the keys once at the end (O(n) expected + O(u log u) for u
distinct words), or count directly in a sorted map (SortedDictionary, TreeMap, std::map), which
costs O(log u) per update. Sorting once is usually faster; the sorted map wins if you need the order
at many points along the way.
3. A breadth-first search needs a FIFO queue. What do you use in each language?
C# Queue<T>; Python collections.deque with append and popleft; Java ArrayDeque with
offer and poll; C++ std::queue (over std::deque). Never a Python list with pop(0).
4. A scheduler repeatedly picks the job with the earliest deadline and adds new jobs. Which structure?
A min-priority queue keyed by deadline: O(log n) to add, O(log n) to remove the earliest. In C++
remember to pass std::greater<> (or invert the comparison), since std::priority_queue is a max-heap
by default.
Summary
List the operations first; the dominant ones pick the structure.
Six structures cover most needs: dynamic array, hash map, hash set, deque, sorted tree, heap.
Every language has them under different names, with gaps: no deque in C#, no sorted collections in
Python's standard library.
Prefer the dynamic array by default: contiguous memory beats linked nodes in practice.
Watch the traps: front removal on a list, linear membership tests, legacy Java types and the max-heap
default in C++.
Full implementation
The teaching cache model in four languages, checked against one shared fixture of address streams (sequential, scattered, LRU eviction), plus each language's own layout guarantee: adjacent int[] elements in C#, a contiguous array.array buffer in Python, references in a Java ArrayList, and &v[i] == v.data() + i in C++.
1usingSystem.Runtime.CompilerServices;23namespaceBekadan.Dsa.Examples.Memory;45/// <summary>6/// Contiguous vs linked layout, and the Memory Lab's teaching cache model7/// (fixed-size lines, a few of them, least recently used evicted). The model is8/// for explaining locality, not for predicting real hardware.9/// </summary>10publicstaticclassContiguousVsLinked11{12 /// <summary>Element i of an array starts at base + i * size.</summary>13publicstaticlong[] ArrayAddresses(longbaseAddress, intcount, intelementSize)14 {15varaddresses=newlong[count];16for (inti=0; i < count; i++)17 {18 addresses[i] = baseAddress + (long)i * elementSize;19 }20return addresses;21 }2223 /// <summary>A list's next address can only be read from the current node (0 = null).</summary>24publicstaticList<long> ListAddresses(longhead, IReadOnlyDictionary<long, long> next)25 {26varaddresses=newList<long>();27for (longnode= head; node !=0;)28 {29 addresses.Add(node);30 node = next.GetValueOrDefault(node);31 }32return addresses;33 }3435 /// <summary>Line loads (misses) for a sequence of reads, in the teaching cache.</summary>36publicstaticintCountMisses(IEnumerable<long> addresses, intlineSize, intcapacity)37 {38varcache=newList<long>(); // least recently used first39intmisses=0;40foreach (longaddressin addresses)41 {42longline= address / lineSize;43intat= cache.IndexOf(line);44if (at >=0)45 {46 cache.RemoveAt(at);47 cache.Add(line);48 }49else50 {51 misses++;52if (cache.Count == capacity) cache.RemoveAt(0);53 cache.Add(line);54 }55 }56return misses;57 }5859 /// <summary>What C# itself guarantees, checked without unsafe code.</summary>60publicstaticvoidCheckLayout()61 {62int[] values=newint[8];63for (inti=0; i < values.Length; i++)64 {65Check(Unsafe.ByteOffset(ref values[0], ref values[i]) == i *sizeof(int), "int[] elements are adjacent");66 }67varlist=newLinkedList<int>([10, 20, 30]);68LinkedListNode<int> second= list.First!.Next!;69Check(second.Value ==20&& second.Previous == list.First, "every LinkedListNode is a separate object linked by references");70 }7172privatestaticvoidCheck(boolcondition, stringclaim)73 {74if (!condition) thrownewInvalidOperationException($"Claim failed: {claim}");75 }76}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Memory/ContiguousVsLinked.cs
1"""Contiguous vs linked layout, and the Memory Lab's teaching cache model.23The model (fixed-size lines, a few of them, least recently used evicted) explains4locality; it does not predict real hardware.5"""67from array import array8from collections.abc import Iterable91011def_check(condition: bool, claim: str) -> None:12ifnot condition:13raiseAssertionError(f"Claim failed: {claim}")141516defarray_addresses(base: int, count: int, element_size: int) -> list[int]:17"""Element i of an array starts at base + i * size."""18 addresses = []19for i inrange(count):20 addresses.append(base + i * element_size)21return addresses222324deflist_addresses(head: int, nxt: dict[int, int]) -> list[int]:25"""A list's next address can only be read from the current node (0 = None)."""26 addresses = []27 node = head28while node !=0:29 addresses.append(node)30 node = nxt.get(node, 0)31return addresses323334defcount_misses(addresses: Iterable[int], line_size: int, capacity: int) -> int:35"""Line loads (misses) for a sequence of reads, in the teaching cache."""36 cache: list[int] = [] # least recently used first37 misses =038for address in addresses:39 line = address // line_size40if line in cache:41 cache.remove(line)42 cache.append(line)43else:44 misses +=145iflen(cache) == capacity:46 cache.pop(0)47 cache.append(line)48return misses495051defcheck_layout() -> None:52"""What Python itself guarantees."""53 numbers = array("i", range(8))54 view =memoryview(numbers)55 _check(view.c_contiguous and view.nbytes ==len(numbers) * numbers.itemsize, "array.array keeps raw numbers in one contiguous buffer")56 shared =object()57 refs = [shared, shared]58 _check(refs[0] is refs[1], "a list stores references: the same object can sit in two slots")
Tested on CPython 3.14.0 · examples/python/dsa_examples/memory_contiguous_vs_linked.py
1package dev.bekadan.dsa.memory;23import java.util.ArrayList;4import java.util.List;5import java.util.Map;67/**8 * Contiguous vs linked layout, and the Memory Lab's teaching cache model (fixed-size9 * lines, a few of them, least recently used evicted). Java exposes no addresses, and10 * the JVM decides object layout; the model explains locality, it predicts nothing.11 */12publicfinalclassContiguousVsLinked {13privateContiguousVsLinked() {14 }1516 /** Element i of an array starts at base + i * size. */17publicstaticlong[] arrayAddresses(longbase, intcount, intelementSize) {18long[] addresses=newlong[count];19for (inti=0; i < count; i++) {20 addresses[i] = base + (long) i * elementSize;21 }22return addresses;23 }2425 /** A list's next address can only be read from the current node (0 = null). */26publicstatic List<Long> listAddresses(longhead, Map<Long, Long> next) {27 List<Long> addresses=new ArrayList<>();28longnode= head;29while (node !=0) {30 addresses.add(node);31 node = next.getOrDefault(node, 0L);32 }33return addresses;34 }3536 /** Line loads (misses) for a sequence of reads, in the teaching cache. */37publicstaticintcountMisses(long[] addresses, intlineSize, intcapacity) {38 List<Long> cache=new ArrayList<>(); // least recently used first39intmisses=0;40for (longaddress: addresses) {41longline= address / lineSize;42intat= cache.indexOf(line);43if (at >=0) {44 cache.remove(at);45 cache.add(line);46 } else {47 misses++;48if (cache.size() == capacity) cache.remove(0);49 cache.add(line);50 }51 }52return misses;53 }5455 /** An int[] holds the numbers; an ArrayList holds references to objects. */56publicstaticvoidcheckLayout() {57int[] values= {10, 20, 30};58 values[1] =21;59check(values[1] ==21, "an int[] element is the number itself");60 List<StringBuilder> refs=new ArrayList<>();61 StringBuildershared=newStringBuilder("x");62 refs.add(shared);63 refs.add(shared);64check(refs.get(0) == refs.get(1), "an ArrayList stores references: one object can sit in two slots");65 }6667privatestaticvoidcheck(booleancondition, String claim) {68if (!condition) {69thrownewAssertionError("Claim failed: "+ claim);70 }71 }72}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/memory/ContiguousVsLinked.java
1#pragmaonce23#include<algorithm>4#include<cassert>5#include<cstddef>6#include<cstdint>7#include<iterator>8#include<list>9#include<unordered_map>10#include<vector>1112namespacebekadan::dsa::memory {1314// Contiguous vs linked layout, and the Memory Lab's teaching cache model (fixed-size15// lines, a few of them, least recently used evicted). The model explains locality;16// it does not predict real hardware.1718// Element i of an array starts at base + i * size.19inlinestd::vector<std::uint64_t> array_addresses(std::uint64_tbase, intcount, intelement_size) {20std::vector<std::uint64_t> addresses(static_cast<std::size_t>(count));21for (int i =0; i < count; ++i) {22 addresses[static_cast<std::size_t>(i)] = base +static_cast<std::uint64_t>(i) *static_cast<std::uint64_t>(element_size);23 }24return addresses;25}2627// A list's next address can only be read from the current node (0 = nullptr).28inlinestd::vector<std::uint64_t> list_addresses(std::uint64_thead, conststd::unordered_map<std::uint64_t, std::uint64_t>&next) {29std::vector<std::uint64_t> addresses;30for (std::uint64_t node = head; node !=0;) {31 addresses.push_back(node);32constauto it = next.find(node);33 node = it == next.end() ?0: it->second;34 }35return addresses;36}3738// Line loads (misses) for a sequence of reads, in the teaching cache.39inlineintcount_misses(conststd::vector<std::uint64_t>&addresses, std::uint64_tline_size, std::size_tcapacity) {40std::vector<std::uint64_t> cache; // least recently used first41int misses =0;42for (conststd::uint64_t address : addresses) {43conststd::uint64_t line = address / line_size;44if (constauto at =std::find(cache.begin(), cache.end(), line); at != cache.end()) {45 cache.erase(at);46 cache.push_back(line);47 } else {48++misses;49if (cache.size() == capacity) cache.erase(cache.begin());50 cache.push_back(line);51 }52 }53return misses;54}5556// What the standard guarantees: std::vector is a contiguous container; std::list is not.57inlinevoidcheck_layout() {58std::vector<int> v(8);59for (std::size_t i =0; i < v.size(); ++i) assert(&v[i] == v.data() + i);60conststd::list<int> nodes{10, 20, 30}; // one allocation per node; no address relationship is promised61assert(*std::next(nodes.begin()) ==20);62}6364} // namespace bekadan::dsa::memory
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/memory/contiguous_vs_linked.hpp