Data Structure

A collection of data values, the relationships among them, and the operations available on them.

A data structure is a collection of data values, the relationships among them, and the operations that can be performed on those values. It is the organizational layer that algorithms operate on.

Formal View

A data structure is an algebraic structure about data, defined by:

  1. A set of values — the data being stored
  2. Relations — how values are connected (e.g. ordering, parent-child, key-value)
  3. Operations — what you can do (insert, delete, search, traverse)

The choice of data structure determines the time and space complexity of the operations an algorithm needs.

Fundamental Structures

Arrays

  • Fixed-size, contiguous memory
  • O(1)O(1) random access by index
  • O(n)O(n) insertion/deletion (requires shifting)
  • Cache-friendly — spatial locality

Linked Lists

  • Dynamic size, nodes connected by pointers
  • O(1)O(1) insertion/deletion at known node
  • O(n)O(n) access by position
  • Poor cache locality

Hash Tables

  • Key-value store via hash function
  • O(1)O(1) average for insert, delete, lookup
  • O(n)O(n) worst-case (hash collisions)
  • No inherent ordering

Trees

VariantSearchInsertDeleteNotes
BST (unbalanced)O(n)O(n) worstO(n)O(n) worstO(n)O(n) worstDegenerates on sorted input
AVL TreeO(logn)O(\log n)O(logn)O(\log n)O(logn)O(\log n)Height-balanced
Red-Black TreeO(logn)O(\log n)O(logn)O(\log n)O(logn)O(\log n)Used in Linux scheduler
B-TreeO(logn)O(\log n)O(logn)O(\log n)O(logn)O(\log n)Optimized for disk I/O
HeapO(n)O(n)O(logn)O(\log n)O(logn)O(\log n)O(1)O(1) min/max access

Graphs

General structure: vertices VV and edges EE.

  • Adjacency matrixO(1)O(1) edge lookup, O(V2)O(V^2) space
  • Adjacency listO(V+E)O(V + E) space, better for sparse graphs

Choosing a Data Structure

The right structure depends on the dominant operations:

  • Mostly lookups by key → hash table
  • Ordered traversal + balanced ops → balanced BST
  • Priority queue / scheduling → heap
  • Graph traversal (BFS, DFS) → adjacency list
  • Time-series / sliding window → deque or circular buffer