Skip to content

Lesson 3 of 40Foundations

Data Structures Overview

Know the core data structures, what each operation costs, and which built-in to reach for in Python and TypeScript.

20 min read0/4 questions

Most interview problems are solved by picking the right container. Choose a list where you needed a set and your O(n) solution becomes O(n²). This lesson is a map of the structures you will use for the rest of the track: what each one is, what it costs, and what Python and TypeScript give you for free.

You do not need to memorise how each one is built inside. You do need the costs, because they decide your Big-O.

Arrays and dynamic arrays

An array is a row of slots side by side in memory, numbered from 0. Because the slots are evenly spaced, the computer can jump straight to slot i with arithmetic. That makes reading by index O(1).

A dynamic array is an array that grows itself when it fills up (doubling, as you saw in the last lesson). Python's list and JavaScript's Array are both dynamic arrays.

Inserting at the front shifts everything
4
0
8
1
15
2
↑i
16
3
4

Reading nums[2] jumps straight to the slot: O(1).

1/4

Choose it when you need ordered items, fast access by position, and you mostly add or remove at the end.

Linked lists

A linked list is a chain of nodes. Each node holds a value and a pointer to the next node. Nodes can live anywhere in memory, so there is no jumping to index 5: you walk from the head.

A singly linked list: 1 → 2 → 3
NamesObjects in memoryheadListNodeval=1, next=n2ListNodeval=2, next=n3ListNodeval=3, next=None

head points at the first node. Each node points at the next. The last points at None.

1/2

Neither Python nor JS has a built-in linked list you would use day to day, but interviewers love them because they test careful pointer handling. They get their own lesson later in this unit.

Choose it when you insert and remove at known positions often and never need random access. In practice, it is the building block for other structures (queues, LRU caches).

Hash maps and hash sets

A hash map stores key → value pairs. It runs the key through a hash function to get a number, and uses that number to pick a bucket. Finding a key means hashing it again and looking in one bucket, so insert, lookup and delete are O(1) on average.

A hash map of ages
  1. 0empty
  2. 1empty
  3. 2empty
  4. 3empty
  5. 4empty
  6. 5empty

An empty map with 6 buckets.

1/4

A hash set is the same idea with keys only: "have I seen this?" in O(1). Keys must be hashable: in Python that means immutable (strings, numbers, tuples), not lists.

Choose it when you need fast lookup by key, counting, de-duplicating, or "have I seen this before?". This is the single most useful structure in interviews.

Stacks, queues and deques

A stack is last in, first out (LIFO), like a pile of plates: you push onto the top and pop from the top. A queue is first in, first out (FIFO), like a checkout line. A deque (double-ended queue, said "deck") lets you add and remove at both ends in O(1).

A stack after push 1, push 2, push 3
  1. 3 ← top: next to pop
  2. 2
  3. 1 ← bottom: pushed first

Push and pop both happen at the top, so both are O(1).

A queue: in at the back, out at the front
Ada
0
↑front
Sam
1
Leo
2
↑back

Three people waiting. Ada arrived first.

1/3

In Python, a list is a fine stack (append / pop), but list.pop(0) is O(n), so use collections.deque for queues (append / popleft). In JS, an Array is a fine stack (push / pop), but shift() is O(n). For a queue in JS, keep a "head" index into the array instead of shifting, or write a small deque class.

Quick check
You are writing a breadth-first search in Python that removes from the front of a queue up to a million times. What should the queue be?
Need a nudge? A hint rules out a wrong answer.

Heaps

A heap (priority queue) always gives you the smallest item (a min-heap) or the largest (a max-heap) in O(1), and adds or removes items in O(log n). It is stored as an array but shaped like a tree where every parent is smaller than its children.

Pushing 0 into a min-heap
734152

A min-heap. The root 1 is the smallest. Every parent is smaller than its children.

1/4

Python has heapq, which turns a plain list into a min-heap. JavaScript and TypeScript have no built-in heap. In interviews you can say "assume a MinHeap class", sort when the data is small and static, or write a short one (the heaps lesson shows how).

Predict the outputPython

What does this print?

import heapq
h = []
for x in [5, 1, 8, 3]:
  heapq.heappush(h, x)
print(heapq.heappop(h), heapq.heappop(h))
Need a nudge? Hints walk you through it.

Choose it when you repeatedly need the smallest or largest item: "top k", "k closest", scheduling, merging sorted lists, Dijkstra's shortest path.

Trees and binary search trees

A tree is a hierarchy of nodes: one root, each node with children, no loops. A binary tree has at most two children per node. A binary search tree (BST) adds a rule: everything in the left subtree is smaller than the node, everything in the right is bigger. That rule lets you search by going left or right, like binary search.

Searching a BST for 6
13681014

Start at the root. 6 is less than 8, so go left.

1/3

Python and JS have no built-in BST. When you need sorted order with fast inserts, Python developers use bisect on a sorted list or the sortedcontainers package; in interviews you usually build tree nodes yourself.

Tries

A trie (prefix tree, said "try") stores strings letter by letter. Words that share a prefix share a path. Checking whether any word starts with a prefix costs O(length of the prefix), regardless of how many words are stored.

A trie holding cat, car and dog
(root)tend of catrend of caracgend of dogodroot

cat and car share the path c → a. Autocomplete walks the prefix, then lists everything below it.

Graphs

A graph is a set of nodes (vertices) connected by edges. Edges can have a direction (a follows b) or not (a and b are friends), and can carry a weight (a distance). Trees are a special kind of graph. You usually store a graph as an adjacency list: a hash map from each node to its neighbours.

Who knows whom
AdaSamLeoPriyaMia

currentwaitingdone

Five people, five friendships. As an adjacency list: {"Ada": ["Sam", "Leo"], ...}.

1/2

The cost table

Average-case costs. n is the number of items, L is the length of a string key.

StructureAccess by indexSearchInsertDeletePythonTypeScript
Dynamic arrayO(1)O(n)O(1) at end, O(n) elsewhereO(1) at end, O(n) elsewherelistArray
Linked listO(n)O(n)O(1) at a known nodeO(1) at a known nodewrite a ListNodewrite a ListNode
Hash map / setn/aO(1)O(1)O(1)dict, set, Counter, defaultdictMap, Set
Stacktop onlyO(n)O(1) pushO(1) poplistArray
Queue / dequeends onlyO(n)O(1) at either endO(1) at either endcollections.dequeindex pointer or custom class
Heapmin/max in O(1)O(n)O(log n)O(log n) popheapqnone built in
Balanced BSTn/aO(log n)O(log n)O(log n)none (use bisect)none
Trien/aO(L)O(L)O(L)write it with dictswrite it with Maps
Graph (adjacency list)n/aO(V + E) to traverseO(1) add edgeO(degree)dict of listsMap of arrays
Match the pairs0/6 matched

Pick the structure for each job.

Choose an item, then its match on the other side.
Quick check
In a TypeScript interview you need the 3 largest numbers from a stream of a million. What is a reasonable answer?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

First unique character

Return the index of the first character in s that appears exactly once. Return -1 if there is none.

"leetcode"      →  0   ('l')
"loveleetcode"  →  2   ('v')
"aabb"          →  -1
def first_unique(s: str) -> int: pass
Key terms
dynamic array
An array that grows by reallocating into a bigger block. O(1) index access, amortized O(1) append. Python list, JS Array.
hash map
Key → value storage with O(1) average insert, lookup and delete. Python dict, JS Map.
deque
A double-ended queue with O(1) adds and removes at both ends. Python collections.deque.
heap
A tree stored in an array that gives the min (or max) in O(1) and pushes or pops in O(log n). Python heapq; none built into JS.
BST
A binary tree where left is smaller and right is bigger, so search takes O(log n) when balanced.
adjacency list
A graph stored as a map from each node to its list of neighbours.