Fifteen structures, one mental model each
This guide expands the video “Every Data Structure Simply Explained in 25 Minutes” into a written reference. Each section keeps the video's signature example — the spoken picture — rendered as a small animated scene, then goes deeper: the memory layout underneath, the operations and their real costs, and the traps interviewers actually probe.
Wherever a structure exists in the main platform, a link at the bottom of the card opens the live execution-trace visualizer for the same topic, so you can go from the picture to the code. Every card also carries an In Python line naming where the structure lives in the language — which are built in and which you build yourself.
Sources: “Every Data Structure Simply Explained in 25 Minutes!” and “Introduction To Data Structures — Python Tutorials” (Amulya's Academy), English transcripts. Companion to the Interactive Python DS&A Mastery Platform in this repository.
00Why Structures Exist organize → access fast
“A dictionary only works because it is alphabetical.” You open it near the right letter and the word is there — imagine the same dictionary printed in random order. The library is the same idea: books sorted into categories — thriller, horror, romance — so borrowing a book means walking to one shelf, not searching the whole building.
Categories collapse the search space: you skip two thirds of the shelf without looking. Random order means reading every spine.
The definition
A data structure is a way to store and organize data so it can be accessed, used, and manipulated effectively. Organized data is the whole point: the alphabetized dictionary, the genre-sorted library, the numbered seats you will meet in Arrays. Remove the organization and the same information becomes expensive to reach.
Why there are fifteen (and more)
A library can arrange its books hundreds of ways — and each arrangement is a different structure, good at different questions. Lookup by position, fast insertion, ordering, hierarchy, membership, recency: each structure in this guide exists because some question becomes cheap only when data is arranged a particular way. Choosing the right one for the job is one of the most important calls a programmer makes — which is why you learn all of them, then pick.
Python's two drawers
| type | what it is | |
|---|---|---|
| built-in | list | dynamic array — growable, ordered |
| tuple | fixed-size, immutable sequence | |
| set | hash set — unique members, fast membership | |
| dict | hash map — key → value | |
| user-defined | stack | LIFO — usually a plain list |
| queue | FIFO — collections.deque | |
| linked list | nodes wired by pointers | |
| tree | parents and children | |
| graph | vertices and edges |
- Python ships four built-ins; everything else you assemble from them (or import from the stdlib).
- Every card below ends with an In Python line: where that structure actually lives in the language.
01Arrays access O(1)
“Seats in a movie theater.” Every seat has a precise label. If someone asks for seat 47, you don't check seats 1–46 — you walk straight to it.
Index × element size + base address = the exact memory cell. Finding item 40,000 costs the same as item 4.
How it works
An array is a fixed-size, ordered collection where every item sits at a numbered position and
all items live in one contiguous block of memory. Because the layout is uniform, the address of
any element is arithmetic: base + index × size. That is the entire trick behind O(1) access —
there is no search, only a calculation.
The hidden cost
Size is fixed at creation. Growing means allocating a brand-new block and copying every element (dynamic arrays amortize this by doubling). Inserting in the middle shifts every later element one slot. Reading is free; reshaping is not.
Operations
| op | cost | why |
|---|---|---|
| read a[i] | O(1) | address arithmetic |
| write a[i] | O(1) | same |
| append (dyn) | O(1)* | amortized; occasional grow |
| insert middle | O(n) | shift the tail |
| resize | O(n) | new block + copy all |
Watch out
- Contiguity is why arrays are cache-friendly — sequential reads prefetch perfectly.
- “Dynamic array” ≠ magic: growth is real copying, just rare.
In Python: list is the dynamic array — over-allocated so append stays amortized O(1). tuple is its fixed, immutable sibling; array.array packs raw numerics tighter.
02Linked Lists insert O(1) · access O(n)
“A treasure hunt where each clue only tells you where the next clue is.” You can't jump to clue four until you've found clue three.
Every node is two fields: value + pointer. Insertion rewires two pointers — done. Finding node #10,000 means 10,000 hops.
How it works
Nodes are scattered anywhere in memory and stay ordered purely through next pointers
(plus prev for doubly-linked). There is no index, no contiguity, no arithmetic shortcut —
position only exists relative to your current node.
The trade that defines it
Insert/delete at a known position is two pointer writes — O(1), no shifting, no copying. But reaching a position is O(n): start at the head and hop. You gain flexibility and pay for it in access speed — the exact mirror image of an array.
Operations
| op | cost | why |
|---|---|---|
| insert @ head | O(1) | rewire 2 pointers |
| delete @ node | O(1) | bypass the link |
| access a[k] | O(n) | walk from head |
| search | O(n) | no shortcut exists |
Watch out
- Pointer chasing is cache-hostile — real cost is worse than the O(n) suggests.
- Interview classic: find the middle / detect a cycle with fast & slow pointers.
In Python: no built-in linked list — a user-defined structure. You write class Node with self.next; collections.deque uses linked blocks internally but never exposes them.
03Stacks push / pop O(1)
“A stack of plates.” Add to the top, take from the top — nobody pulls from the bottom. Last In, First Out.
Two operations, that's it: push (add on top) and pop (remove the top). The middle is off-limits by design.
How it works
A stack restricts you to one end of one array. That sounds like a limitation — it is, and it's the point. With only one end live, both operations are trivially O(1) and the ordering guarantee (newest first) is structural, not something you have to maintain.
Where it hides
Your call stack runs every function you write: each call pushes a frame, each return pops one — which is why a stack overflow means too many frames. Browser Back, document undo, expression evaluation, bracket matching — all the same rhythm.
Operations
| op | cost | why |
|---|---|---|
| push | O(1) | write the top slot |
| pop | O(1) | drop the top slot |
| peek | O(1) | read top |
| anything else | — | not allowed, by design |
Watch out
- “Recursion” is just the compiler's stack — anything recursive can be rewritten with an explicit one.
- Underflow (pop on empty) is the classic edge case to name.
In Python: the tutorial's "user-defined" stack is just a list in practice — append() pushes, pop() pops, both O(1) at the end.
04Queues enqueue / dequeue O(1)
“A line at a coffee shop.” Whoever arrived first gets served first. You join at the back, you wait your turn — no cutting.
Enqueue adds at the back; dequeue removes from the front. Same two operations as a stack, opposite behavior.
How it works
A queue keeps a front pointer and a back pointer — usually over a circular buffer or a linked list. Each operation touches exactly one end, so both are O(1). A stack is a to-do list where you always do the newest task; a queue is one where you always finish what started first.
Where it hides
Anywhere work must be fairly ordered: printer spoolers, web servers absorbing a burst one request at a time, keyboard input buffers, BFS traversal (the frontier is a queue), message brokers and task pipelines.
Operations
| op | cost | why |
|---|---|---|
| enqueue | O(1) | write at back |
| dequeue | O(1) | take from front |
| peek front | O(1) | read front |
| middle access | — | not allowed |
Watch out
- Array-backed queues need a circular buffer or dequeue becomes O(n) shifting.
- BFS uses a queue; DFS uses a stack — the data structure is the traversal order.
In Python: collections.deque for single-threaded work (append/popleft); queue.Queue adds locking when producers and consumers live on different threads.
05Deque both ends O(1)
“A train where passengers board and exit from either side.” Both ends are live, all the time.
Use only the back → it's a stack. Add back + remove front → it's a queue. A deque is both at once.
How it works
A double-ended queue supports push/pop on both ends in O(1) — typically a circular buffer or a doubly-linked list underneath. It is strictly more flexible than a stack or a queue, and it is the shape-shifter: restrict it to one end and you get a stack; add-back/remove-front and you get a queue.
The signature use: sliding windows
When data flows continuously — new values in one end, expired values out the other — a deque is
the only clean fit. The classic interview problem sliding window maximum keeps a deque of
candidate indices, popping expired/front losers in amortized O(1) per element.
Operations
| op | cost | why |
|---|---|---|
| push_front / push_back | O(1) | either end live |
| pop_front / pop_back | O(1) | either end live |
| peek both | O(1) | both pointers |
| middle access | — | still off-limits |
Watch out
- Python's
collections.dequeis exactly this —appendleft/popleftare O(1) wherelistis O(n).
In Python: collections.deque — the tutorial's "user-defined" queue structure ships ready-made in the standard library.
06Hash Maps get / put ~O(1)
“You search mom in your phone contacts — her number appears instantly.” No scrolling, no waiting. The key is the address.
The hash function turns any key into a slot number. Storing and finding are the same jump — no scan ever.
How it works
A hash map stores key → value pairs. On write, the key goes through a hash function — a deterministic formula producing a slot index — and the value lands in that slot (or a bucket hanging off it). On read, the same formula reproduces the slot instantly. The size of the collection basically stops mattering.
The one wrinkle: collisions
Two different keys can hash to the same slot — a collision. Maps resolve it with chains (a small list per slot) or probing (try the next slot). With a good hash and a sane load factor, collisions are rare and lookup stays effectively O(1); pathological input can degrade it to O(n), which is why hash-flood attacks are a real thing.
Operations
| op | avg | worst |
|---|---|---|
| put(k,v) | O(1) | O(n) collisions |
| get(k) | O(1) | O(n) |
| delete(k) | O(1) | O(n) |
| iterate keys | O(n) | unordered! |
Watch out
- No ordering — iteration order is not insertion order (and not sorted).
- Costs more memory than a list: slots stay empty to keep collisions low.
In Python: dict — one of the four built-ins. Since 3.7 it also preserves insertion order, a language guarantee.
07Hash Sets membership O(1)
“A nightclub guest list.” The bouncer doesn't care about your table number — only whether you're on the list. Yes or no, instantly.
A hash map with the values stripped off — only keys remain. Membership, add, remove: all O(1).
How it works
Strip the value out of a hash map and a hash set remains: each key hashes to a slot, and the slot being occupied is the answer. Every element appears exactly once — inserting a duplicate is a no-op by construction, which makes deduplication a one-liner.
When it beats a list
Checking membership in an unsorted list is O(n) every time; a set answers instantly regardless of size. The recurring pattern: not storing more, just knowing whether it's there.
Operations
| op | cost |
|---|---|
| contains(k) | O(1) |
| add(k) | O(1) |
| remove(k) | O(1) |
| union / intersect | O(n) / O(min) |
Watch out
- Same hash-map caveats: unordered, extra memory, worst case degrades on collisions.
In Python: set and its immutable twin frozenset — the third built-in data structure after list and tuple.
08Trees hierarchy, one root
“Open your file explorer.” One starting point at the top, folders splitting into folders, eventually into files. Every path flows one direction — root to leaves.
Exactly one root; every node has one parent (except the root); leaves have no children; no cycles, ever.
How it works
A tree models parent–child relationships: one root, edges pointing downward, leaves at the bottom. Two invariants make it a tree and not a graph: exactly one path exists between any two nodes, and there are no cycles.
Where it hides
File systems, the DOM (every HTML tag a node), comment threads, org charts, JSON/XML documents, decision trees in ML. A plain tree has no ordering rule — searching means visiting every node, which is exactly the gap the next structure closes.
Vocabulary
| root | the single top node |
| leaf | a node with no children |
| depth | edges from the root |
| height | longest root→leaf path |
| subtree | a node + all below it |
Watch out
- Traversal choice matters: DFS (pre/in/post-order) vs BFS (level order).
In Python: no built-in tree — user-defined, per the tutorial's split. Nested dicts, class hierarchies, and xml.etree all carry the same shape.
09Binary Search Trees search O(log n)*
“The number guessing game.” Guess 500 → too high → only 1–499 remain. Every guess eliminates half the possibilities. Left is always smaller, right is always larger.
Each comparison discards an entire subtree. The structure does the pruning for you.
How it works
One rule, applied recursively: left subtree < node < right subtree. Searching starts at the root; each comparison sends you left or right, eliminating half the remaining tree. In a balanced BST, search/insert/delete are all O(log n) — a million nodes in ~20 steps.
The hidden weakness
Feed it already-sorted input (1, 2, 3, 4…) and every node gets only a right child — the “tree” degenerates into a linked list and operations fall back to O(n). That's why self-balancing variants (AVL, red-black) exist: they pay a small rotation cost to keep height ≈ log n guaranteed.
Operations
| op | balanced | degenerate |
|---|---|---|
| search | O(log n) | O(n) |
| insert | O(log n) | O(n) |
| delete | O(log n) | O(n) |
| in-order walk | O(n) | yields sorted output |
Watch out
- The invariant is on all descendants, not just direct children — a classic invalid-BST trap.
- “In-order traversal = sorted sequence” is the property most problems exploit.
In Python: no built-in BST either — the practical stand-in is a sorted list plus the bisect module for O(log n) lookups.
10Heaps top O(1) · push/pop O(log n)
“An emergency room.” The heart-attack patient jumps the line ahead of the headache — urgency beats arrival time, automatically.
Only the top is guaranteed. Everything else is “almost sorted” — enough to restore the top in O(log n) after every change.
How it works
A heap is a complete binary tree (usually stored flat in an array: children of i at
2i+1, 2i+2) with one invariant — every parent outranks its children. Max-heap →
largest on top; min-heap → smallest. Insert bubbles up; removing the top drops the last element
into the hole and sinks it down. Both fix the invariant in O(log n).
Why not just sort?
Sorting a changing list costs O(n log n) every time. A heap keeps only the promise you actually need — “the most important item is at the top, right now” — for O(log n) per update and O(1) per peek.
Operations
| op | cost |
|---|---|
| peek top | O(1) |
| push | O(log n) |
| pop top | O(log n) |
| heapify(array) | O(n) |
Watch out
- “Heap” the structure ≠ “heap” the memory region — same word, unrelated things.
- A heap is not sorted — only the root is special.
In Python: the heapq module — a min-heap over a plain list: heappush, heappop, heapify, nsmallest.
11Tries prefix ops O(len)
“Type app into Google.” Before you finish, apple, application, appointment appear — the structure already knows which branch you're heading down.
Each level is one character. Three letters typed = three steps taken = you're standing on the subtree of every completion.
How it works
A trie stores words as paths of characters: shared prefixes share nodes, and an end-of-word flag marks where a real word terminates. Lookup and insert cost O(word length) — independent of how many words exist.
Why it beats a hash map here
A hash map answers exact lookups instantly — but “everything starting with app”
forces a full scan. A trie answers prefix queries in exactly as many steps as the prefix is long, and
the matching completions are already the subtree below you.
Operations
| op | cost |
|---|---|
| insert(word) | O(len) |
| search(word) | O(len) |
| startsWith(p) | O(len) |
| list completions | O(subtree) |
Watch out
- Memory-heavy: one node per character. Compressed (radix) tries merge single-child chains into edge strings.
- It's pronounced “try” — from retrieval.
In Python: user-defined — the common idiom is nested dicts keyed by character, or a small Node class with a children map and an end-of-word flag.
12Graphs BFS / DFS O(V+E)
“Facebook is a giant graph.” You're a node, friends are nodes, every friendship an edge. Google Maps: cities are nodes, roads are edges.
Dots (vertices) + lines (edges). BFS expands like a ripple — everyone one hop away, then two, then three.
How it works
Forget clean hierarchies — graphs model relationships going in every direction, cycles included. Undirected edges go both ways (friendships); directed edges have an arrow (Twitter follows). Two nodes sharing an edge are adjacent.
Two ways to store one
Adjacency matrix: a grid, 1 where an edge exists — O(1) edge check but O(V²) space.
Adjacency list: each node lists its neighbors — compact for sparse graphs, which is nearly all
real ones. Traversals are BFS (queue, level by level → shortest unweighted path) and DFS
(stack/recursion → cycles, components, topological order).
Core operations
| op | cost |
|---|---|
| BFS / DFS | O(V+E) |
| shortest path (unw.) | O(V+E) |
| Dijkstra (weighted) | O(E log V) |
| cycle detect / topo | O(V+E) |
Watch out
- Always track visited — cycles will loop a naive traversal forever.
In Python: user-defined — adjacency lists as dict[node, list] or dict[node, set] cover nearly every interview graph.
13Disjoint Set (Union-Find) ~O(1) per op
“A party of 100 people — does Peter know Bob?” Peter knows Carol, Carol knows Dave, Dave knows Bob. Same group? Compare their leaders instead of tracing the chain.
Every element starts alone; connecting two merges their groups. Same leader = same group. Path compression makes it faster the more you use it.
How it works
Each group is a small tree pointing to a representative (leader). find(x) walks
parent pointers to the leader; union(a,b) makes one leader parent of the other. Two
optimizations turn it near-constant: path compression (re-point nodes straight at the leader as
you pass) and union by rank (attach the shorter tree under the taller). Result: amortized
O(α(n)) per operation — effectively O(1) even after millions of merges.
When it's the answer
Any “are these two things connected?” question over groups that keep merging: network connectivity, connected components, image segmentation (same-object pixels), reachability in game worlds, Kruskal's minimum spanning tree.
Operations
| op | cost |
|---|---|
| find(x) | ~O(1) |
| union(a,b) | ~O(1) |
| connected? | ~O(1) |
Watch out
- It answers whether two nodes connect — not how (no path reconstruction).
- Merges only — there's no efficient “split a group”.
In Python: user-defined — a parent list (or dict) plus find and union is the whole structure; under ~20 lines.
14Bloom Filter tiny memory · lies one way
“The data structure that occasionally lies to you.” If it says no, the item is guaranteed absent. If it says yes… it's probably there. Probably.
k hash functions set k bits. Query: all k bits set → “probably yes”; any zero → “definitely no”.
How it works
A bloom filter is a bit array + k hash functions. Insert sets the k bits the key hashes to. Query checks those k positions: any 0 → guaranteed absent (a set bit can't un-set); all 1 → probably present, because other keys may have set those bits — a false positive. It only ever lies in one direction, and never says no to something actually there.
Why tolerate the lie
Gigabytes of items compress into megabytes of bits with O(1) checks. The filter sits in front of expensive work: “definitely not” skips the disk read, the dictionary lookup, the network call. The small lie rate buys enormous speed — tunable via size and k.
Properties
| op | cost |
|---|---|
| add(key) | O(k) |
| maybe-contains | O(k) |
| false negatives | never |
| false positives | tunable, ~1% |
Watch out
- No deletion — clearing a bit could evict other keys (counting filters fix this).
- You can't list what's inside; it answers only membership.
In Python: not in the stdlib — packages like pybloom_live, or ~40 lines with a bytearray and hashlib.
15LRU Cache get / put O(1)
“How your computer decides what to forget.” Limited space; what you use stays, what you haven't touched in forever gets evicted — least recently used first.
Access something → it moves to the front. Out of space → chop the back. Simple, brutally efficient.
How it works
LRU is a composition, not a single structure — that's why interviewers love it. A hash map gives O(1) lookups; a doubly-linked list keeps recency order (most-recent front, least-recent back). Every access unlinks the node and re-links it at the front in O(1). Eviction removes the tail — the entry untouched for the longest time, on the theory that if it wasn't needed lately, it probably isn't needed now.
Where it hides
CPU caches, browser caches, database buffer pools, OS page replacement — anywhere a system must remember things but can't afford to remember everything.
Operations
| op | cost |
|---|---|
| get(k) | O(1) |
| put(k,v) | O(1) |
| evict | O(1) |
Watch out
- A get also refreshes recency — reads mutate the order.
- The classic interview task is implementing both halves correctly: map entry ↔ list node.
In Python: functools.lru_cache decorates any function; the manual version is collections.OrderedDict with move_to_end — dict + ordering, the two halves in one.
∑Cheat sheet — pick the structure by the question it answers
| structure | answers | star op | weak spot | in Python |
|---|---|---|---|---|
| Array | “what's at index i?” | read O(1) | insert/resize O(n) | list · tuple |
| Linked list | “insert/delete fast” | mutate O(1) | access O(n) | build: class Node |
| Stack | “what happened last?” | push/pop O(1) | one end only | list.append/pop |
| Queue | “who's been waiting longest?” | enq/deq O(1) | one end each way | collections.deque |
| Deque | “…or either end?” | both ends O(1) | specialist | collections.deque |
| Hash map | “value for this key?” | get/put ~O(1) | unordered, collisions | dict |
| Hash set | “is it in there?” | membership O(1) | keys only | set · frozenset |
| Tree | “who is below whom?” | O(n) scan | no ordering rule | build: nested dicts |
| BST | “is x in sorted data?” | O(log n)* | degenerates on sorted input | bisect + sorted list |
| Heap | “what's most urgent?” | top O(1) | only the top is sorted | heapq |
| Trie | “words starting with…?” | prefix O(len) | memory heavy | build: nested dicts |
| Graph | “how is x connected to y?” | BFS/DFS O(V+E) | everything is custom | build: dict of lists |
| Union-find | “same group?” | ~O(1) | no paths, no splits | build: parent list |
| Bloom filter | “definitely not there?” | O(k), tiny | false positives, no delete | pybloom_live |
| LRU cache | “keep the hot, drop the cold” | get/put O(1) | bounded by design | functools.lru_cache |
The pattern underneath all fifteen: every structure trades one thing for another — access speed for flexibility, memory for time, exactness for space. Choosing a data structure is choosing which promise you need kept.