Basic Data Structures

Ten structures that most programs are built from, each drawn the way you would sketch it on a whiteboard: what it looks like inside, what every operation costs, and when to reach for it. Each card ends with the Java class to use.

I need to…

Start from what you need to do, and jump to the structure that does it cheaply.

The structures

Green is constant time, amber logarithmic, red linear in the number of items. Blue grows with something else: the length of a word or the number of neighbors. * means on average over many calls.

Array

A fixed row of equal sized slots in one block of memory. The position of any slot is a sum, so reaching it takes one step.

729491[0]100[1]104[2]108[3]112[4]116[5]120addressa[3] lives at 100 + 4 × 3 = 112one calculation, no search: O(1)insert in the middle: shift everything after it
read or write a[i]O(1)find a valueO(n)insert or delete in the middleO(n)
Reach for it when
  • You know the size, or the values are small numbers you can use as the index
  • Counting: letters, digits, buckets
  • Grids, matrices and DP tables

In Java: int[], char[], boolean[]. See int[] counts.

Dynamic array

An array that grows: it keeps spare room at the end, and when that runs out it copies everything into a bigger array.

38517size 5capacity 6add(7) at the end: O(1)full? copy into an array 1.5 × as big385172the copy is rare, so add is O(1) on average
get(i), set(i)O(1)add at the endO(1)*insert or remove in the middleO(n)
Reach for it when
  • The default list: build a result, then read it by index
  • Adjacency lists for graphs
  • A backtracking path: add, recurse, remove the last

In Java: ArrayList.

Linked list

Separate nodes, each pointing to the next one (and in a doubly linked list, the previous one). No index: to reach a node you walk to it.

ABCheadtailnextprevadd or remove at either end: O(1)get(i): walk i nodes: O(n)every node is its own object on the heap
add or remove at either endO(1)insert or remove next to a node you holdO(1)get(i), find a valueO(n)
Reach for it when
  • You already hold the node: an LRU cache moves it to the front in O(1)
  • Splicing lists together without copying
  • Rarely as a plain list: an array is faster in practice

In Java: LinkedList, or your own node class for an LRU cache.

Stack

One open end: you push on top and pop from the top. The last item in is the first one out.

ABCpush(C)pop() gives Clast in, first outpush, pop, peek: O(1)undo, brackets, DFS
push, pop, peekO(1)see anything below the topO(n)
Reach for it when
  • Undo, the call stack, matching brackets
  • Depth first search without recursion
  • Monotonic stack: next greater element

In Java: ArrayDeque with push, pop, peek. Not Stack.

Queue

Two ends: add at the back, take from the front. The first item in is the first one out. A ring buffer does it in an array.

CDAB01234567headtailthe end wraps round to the startadd or remove at either end: O(1)
offer at the back, poll at the frontO(1)peek at the frontO(1)find a valueO(n)
Reach for it when
  • Breadth first search, level by level
  • Jobs waiting for a worker
  • Sliding windows (a deque, open at both ends)

In Java: ArrayDeque; between threads, a BlockingQueue.

Hash table

An array of buckets. A hash of the key picks the bucket, so finding a key is one jump plus a look at the few keys that share it.

01234cat: 3dog: 7ant: 1bee: 5hash(key) % 5 picks the bucketget, put, contains: O(1) on averageover 75% full: double the buckets
get, put, removeO(1) avgthe same, all keys in one bucketO(n)keys in sorted orderno
Reach for it when
  • Look up by key: users by id, counts by word
  • Seen it before? Visited sets, duplicates
  • Two Sum: remember what you have passed

In Java: HashMap and HashSet.

Binary search tree

Each node keeps smaller keys on its left and bigger keys on its right. Kept balanced (for example as a red-black tree), its height stays about log n.

5101520253040ceiling(17): 17 < 20 left, 17 > 10 right, 17 > 15: 20smaller left, bigger right; red-black keeps it O(log n)
find, insert, removeO(log n)smallest, largest, next biggerO(log n)all keys in orderO(n)
Reach for it when
  • Keep things sorted while they change
  • Floor and ceiling: the nearest key below or above
  • Ranges: every booking between two times

In Java: TreeMap and TreeSet.

Heap

A tree where every parent is smaller than its children, stored in an array. The smallest item is always at the top.

135741357401234the same heap as an arraychildren of i: 2i + 1, 2i + 2peek the smallest: O(1)offer, poll: O(log n)
peek the smallestO(1)add, remove the smallestO(log n)find any other valueO(n)
Reach for it when
  • Top k and kth largest
  • Merging k sorted lists
  • Dijkstra and schedulers: always take the cheapest next

In Java: PriorityQueue, a min heap by default.

Graph

Things (vertices) and the links between them (edges). Usually stored as an adjacency list: for each vertex, the vertices it connects to.

ABCDAB, CBA, DCA, DDB, Cadjacency list: O(V + E) memorya V × V matrix only when the graph is dense
neighbors of a vertexO(degree)is there an edge u to v? (list)O(degree)is there an edge u to v? (matrix)O(1)
Reach for it when
  • Networks, maps, dependencies, social graphs
  • Breadth first for the fewest steps, depth first to explore
  • Course schedules: topological order

In Java: List<List<Integer>> or Map<Integer, List<Integer>>, built from ArrayList or HashMap.

Trie

A tree of letters: each word is a path from the root, and words that start the same share the start of their path.

cdaortgcar, cat, doggreen: a wordends hereprefix "ca"→ car, catfind a word: one step per letter, O(length)
insert or find a wordO(length)every word with a prefixO(prefix + matches)memorya node per letter
Reach for it when
  • Autocomplete and search suggestions
  • Word games: Word Search II, Boggle
  • Routing tables: longest matching prefix

In Java: No built in class: a Node with Node[26] children, or a HashMap of children for any alphabet.

Complexity at a glance

The cost of each everyday operation. "avg" assumes a good hash; a bad one puts every key in one bucket and makes it O(n).

StructureReach an itemFind a valueAddRemoveExtra memory
ArrayO(1)O(n)O(n)O(n)none
Dynamic arrayO(1)O(n)O(1)* at the endO(n)spare room at the end
Linked listO(n)O(n)O(1) at the endsO(1) at the endsa node object per item
Stacktop onlyO(n)O(1)O(1)none in an array
Queuefront onlyO(n)O(1)O(1)none in a ring buffer
Hash tableby keyO(1) avgO(1) avgO(1) avgmore buckets than keys
Binary search treeby keyO(log n)O(log n)O(log n)two child links per item
Heapsmallest onlyO(n)O(log n)O(log n) smallestnone in an array
Graphby vertexO(degree)O(1) per edgeO(degree)O(V + E) as a list
Trieby prefixO(length)O(length)O(length)a node per letter

Going further: the Java Collections Field Guide has the same sketches next to each Java class, with what each one costs and the mistake people make with it.

Related in the Lab Java Collections Field Guide · BFS and DFS · LRU and LFU Cache · Kth Largest Element

© 2026 Arman Ajabkhani · armantik.com · Privacy