Skip to main content

Data Structures โ€” Overview

Overviewโ€‹

A data structure is a decision about which operations you want to be cheap. There is no structure that makes everything fast; each one buys speed on some operations by giving it up on others, and picking well means knowing which operations your code actually performs most.

In This Sectionโ€‹

  • Arrays & Dynamic Arrays โ€” contiguous memory, O(1) indexing, and the amortized cost of growth.
  • Linked Lists โ€” O(1) splicing, and why they lose to arrays more often than textbooks suggest.
  • Stacks & Queues โ€” restricted access disciplines, LIFO and FIFO.
  • Hash Tables โ€” expected O(1) lookup, collisions, and load factor.
  • Trees & Binary Search Trees โ€” hierarchical structure and ordered traversal.
  • Balanced Trees โ€” AVL, red-black, B-trees, tries: keeping depth logarithmic.
  • Heaps & Priority Queues โ€” cheap access to the smallest or largest element.
  • Graphs โ€” representing arbitrary relationships, and the cost of each representation.

Complexity at a Glanceโ€‹

Average case, with worst case in parentheses where it differs materially:

StructureAccessSearchInsertDeleteSpace
ArrayO(1)O(n)O(n)O(n)O(n)
Dynamic arrayO(1)O(n)O(1) amortized at endO(n)O(n)
Singly linked listO(n)O(n)O(1) at a known positionO(1) at a known positionO(n)
Stack / QueueO(n)O(n)O(1)O(1)O(n)
Hash tableโ€”O(1) (O(n))O(1) (O(n))O(1) (O(n))O(n)
Binary search treeO(log n) (O(n))O(log n) (O(n))O(log n) (O(n))O(log n) (O(n))O(n)
Balanced BSTO(log n)O(log n)O(log n)O(log n)O(n)
Binary heapO(1) for min/maxO(n)O(log n)O(log n)O(n)
This table lies by omission

It counts operations, treating every memory access as equally expensive. On real hardware they are not: a sequential array scan can outrun a linked-list traversal of the same length by an order of magnitude, because one prefetches perfectly and the other chases pointers into cache misses. Use the table to rule structures out, then measure.

How to Chooseโ€‹

If you mostlyโ€ฆUseBecause
Index by position, iterate in orderDynamic arrayO(1) access, contiguous and cache-friendly
Look things up by keyHash tableExpected O(1), no ordering maintained
Need keys in sorted order, or range queriesBalanced BSTO(log n) with ordered traversal
Repeatedly take the smallest/largestHeapO(1) peek, O(log n) extract
Insert and remove at both endsDequeO(1) at either end
Model relationships between entitiesGraphEverything else is a special case of this