CS50 Data Structures Overview
Data Structures
đŚ Abstract Data Types
An abstract data type (ADT) is a high-level description of a data structure that specifies certain properties and operations, while leaving the underlying implementation details to the programmer. The same ADT can be implemented using different low-level mechanisms (arrays, pointers, etc.).
Queue (FIFO)
A queue follows the first-in, first-out (FIFO) principle. Items are processed in the exact order they arrive â like a line of people at a store.
Enqueue: add an item to the back of the queue
Dequeue: remove an item from the front of the queue
Implementation with an array:
typedef struct {
person people[CAPACITY];
int size;
} queue;Uses a fixed-capacity array plus a
sizecounter to track current occupancy.The array stores data contiguously in memory.
Operations must enforce FIFO order via loop direction or index management.
FIFO = first in, first out â also described as "first come, first served."
Stack (LIFO)
A stack follows the last-in, first-out (LIFO) principle. The most recently added item is the first to be removed â like a pile of plates or an email inbox where the newest message appears at the top.
Push: add an item to the top of the stack
Pop: remove the item from the top of the stack
Implementation with an array:
typedef struct {
person people[CAPACITY];
int size;
} stack;Looks identical to the queue structure, but the push/pop logic treats the array as a LIFO structure.
Real-world example: Gmail/Outlook inbox â newest emails appear first ("last in, first out").
LIFO = last in, first out â no fairness guarantee; the last arrival gets served first.
âď¸ Arrays vs. Linked Lists
The Problem with Fixed-Size Arrays
Arrays store data contiguously in memory, making them fast for random access (O(1)) and efficient for binary search (O(logn)). However, arrays have a fundamental limitation:
Fixed capacity: once allocated, the size cannot change.
Adding a fourth element to a size-3 array requires finding a larger contiguous block, copying all existing data (cost = O(n)), freeing the old block, and fixing all references. This is expensive if done repeatedly.
// Example: growing an array manually
int *list = malloc(3 * sizeof(int));
list[0] = 1; list[1] = 2; list[2] = 3;
// Need to add a fourth number
int *tmp = malloc(4 * sizeof(int));
if (tmp == NULL) { free(list); return 1; }
for (int i = 0; i < 3; i++) tmp[i] = list[i];
tmp[3] = 4;
free(list);
list = tmp;Simple idea â messy code. This pattern is brittle and slow when many insertions are needed.
Alternative: pre-allocate a huge array (wastes memory, and still runs into the same limit eventually).
Linked Lists: A Dynamic Solution
A linked list stores data in separate chunks of memory called nodes, each containing the data and a pointer to the next node. This avoids the contiguity requirement.
Node structure (C code):
typedef struct node {
int number;
struct node *next;
} node;The
nextpointer isNULLfor the last node.An extra pointer called
listorheadpoints to the first node; initiallyNULL.
Visual representation:
list â [1|â˘] â [2|â˘] â [3|NULL]Each box is a node; the dot represents the
nextpointer; arrows show links.
Three Insertion Strategies
Prepend (constant time O(1)) â add new node at the beginning:
n->next = list; list = n;Very fast, but the list ends up in reverse order of insertion.
Append (linear time O(n)) â add new node at the end:
First traverse the entire list to find the last node, then set its
nextto the new node.Requires a loop to reach the end; cost grows with list size.
Sorted insertion (linear time O(n)) â maintain ascending order:
Traverse the list, comparing the new value against each nodeâs number.
Insert at the correct position (before a larger node or at end).
Code must handle three cases: empty list, before first node, middle/end.
Example logic:
If new number < first number â prepend.
Otherwise: walk until
ptr->nextisNULLorptr->next->number> new number, then splice in.
Searching a Linked List
Linear search: start at head, follow
nextpointers until the target is found orNULLis reached.Running time: O(n) in the worst case (target at the end or not present).
Binary search impossible because nodes are not contiguous; you cannot jump to the middle.
Tradeâoff Summary
Property | Array | Linked List |
|---|---|---|
Memory | Contiguous; fixed capacity | Nonâcontiguous; grows dynamically |
Random access | O(1) | O(n) |
Insertion (prepend) | O(n) (copy) | O(1) |
Insertion (append/sorted) | O(n) (copy) | O(n) (traverse) |
Search | O(logn) (if sorted) | O(n) |
Space overhead | None | One pointer per node |
đł Binary Search Trees
A binary search tree (BST) combines the sorting advantage of arrays with the dynamic flexibility of linked lists. Each node has two pointers (left and right) instead of one.
Node structure:
typedef struct node {
int number;
struct node *left;
struct node *right;
} node;Property: For every node, all values in its left subtree are smaller, and all values in its right subtree are larger.
The top node is the root; bottom nodes with no children are leaves.
4
/ \
2 6
/ \ / \
1 3 5 7This is a balanced BST: height = 3, n=7, search cost = O(logn).
Searching a BST
Recursive algorithm:
Base case: if tree is
NULL, returnfalse.If target < rootâs number â search left subtree.
If target > rootâs number â search right subtree.
Else â return
true(found).
bool search(node *tree, int number) {
if (tree == NULL) return false;
if (number < tree->number)
return search(tree->left, number);
else if (number > tree->number)
return search(tree->right, number);
else
return true;
}Each recursive call halves the search space (on average), giving O(logn) time.
This works because the tree is recursive by nature: a subtree is itself a BST.
The Problem of Unbalanced Trees
If data is inserted in sorted order (e.g., 1, 2, 3, 4, âŚ), the BST degenerates into a linked list:
1
\
2
\
3
\
4Searching becomes O(n) because there is no branching.
Selfâbalancing trees (e.g., AVL, redâblack) are used in practice to maintain O(logn) height by rearranging nodes during insertions and deletions.
đ§ Hash Tables
A hash table is a data structure that provides nearâconstantâtime search, insertion, and deletion. It combines an array (for fast indexing) with linked lists (to handle collisions).
Idea: Use a hash function to map each key (e.g., a name) to an array index. Store the keyâvalue pair at that index. If two keys hash to the same index (collision), chain them in a linked list.
Structure:
An array of size m, where each element is a pointer to the head of a linked list (initially
NULL).Each node in the linked list contains the key, the value, and a
nextpointer.
[0] â NULL
[1] â NULL
[2] â [Mario|617-...|â˘] â [Mona|212-...|NULL]
...
[25] â [Zelda|415-...|NULL]Here, names starting with 'M' are stored in bucket 12 (if A=0, M=12). Mario and Mona collide; they are chained.
Hash Functions
A hash function takes a key and returns an integer (the bucket index) in the range [0,mâ1].
Simple example (first letter only):
unsigned int hash(const char *word) {
return toupper(word[0]) - 'A'; // 0â25
}Better hash functions use multiple characters to spread keys more uniformly and reduce collisions.
The output should be deterministic and fast to compute.
Collision Resolution
Separate chaining: each bucket contains a linked list of entries whose keys hash to the same index.
Open addressing: if a slot is taken, probe for the next empty slot (not covered in detail here).
Running Time
Best case: O(1) â every key has a unique bucket (ideal hash function, no collisions).
Average case: O(1+Îą) where Îą=n/m is the load factor. With a good hash and enough buckets, Îą is small.
Worst case: O(n) â all keys hash to the same bucket, forming one long linked list.
In practice, hash tables are extremely fast for dictionaries, symbol tables, and databases.
A dictionary is an abstract data type that stores keyâvalue pairs. Hash tables are a common implementation of dictionaries.
Tradeâoff
Time vs. space: larger arrays (more buckets) reduce collisions but use more memory. A wellâdesigned hash function balances both.
đ˛ Tries
A trie (short for "retrieval") is a treeâbased data structure where each node is an array of pointersâone per possible next character. It excels at stringâkey operations, achieving constantâtime search independent of the number of stored keys.
Node structure:
typedef struct node {
char *number; // or other value (NULL if not terminal)
struct node *children[26]; // 26 letters; NULL means no path
} node;The root is a single node with 26
NULLpointers.To insert a word like "TOAD":
Start at root.
Use first letter 'T' â follow
children[19](assuming A=0). IfNULL, allocate a new node.Move to that node. Use second letter 'O' â follow
children[14]. Allocate if needed.Continue for 'A' and 'D'. At the final node, store the value (e.g., phone number) in the
numberfield.
Words that share a prefix share the same path. For example, "TOAD" and "TOADETTE" both go through TâOâAâD. At the D node, two branches appear: one for 'E' (Toadette) and one where the value is stored (Toad).
Searching
Follow the path letter by letter. If any pointer along the path is
NULL, the word is not present.If you reach a node with a nonâ
NULLvalue, the word exists.Number of steps = length of the word (a constant, e.g., ⤠30 for most names). This is O(k) where k is the maximum key length, effectively O(1).
Running Time
Search: O(k) = O(1) (constant per operation, independent of the total number of keys n).
Insert: O(k) = O(1) (same logic).
Space: Huge â each level potentially adds 26 pointers per node, most of which are
NULL. A trie for a dictionary with thousands of names can consume gigabytes of memory, making it impractical for many applications.
Tradeâoff: Tries give constantâtime operations at the cost of extreme memory consumption. Hash tables are the more common choice for realâworld dictionaries.
đ RealâWorld Application
A hash table appears even in everyday life. A salad shop (e.g., Sweetgreen) uses shelves labeled alphabetically by customer first name. Each shelf acts as a bucket; multiple salads for the same letter form a "linked list" (stacked on the shelf or overflowed to adjacent letters). The system works well at typical loads but degrades when many customers share a first letter (e.g., many Davids). This illustrates the collision problem â and the tradeâoff between simplicity and worstâcase performance.
đĄ Key Takeaways
Abstract data types (queue, stack, dictionary) can be implemented with various underlying structures.
Arrays give fast random access and binary search but are inflexible to grow.
Linked lists grow dynamically and support O(1) prepend insertion but lose binary search.
Binary search trees offer O(logn) search if kept balanced; unbalanced trees degrade to O(n).
Hash tables provide nearâconstant averageâtime operations using buckets and linked lists; worst case is O(n).
Tries guarantee constantâtime search with an enormous memory footprint.
Every data structure involves a timeâspace tradeâoff â the programmer must choose the right tool for the problem.

Ask anything
We've read this whole study set, so questions about it get the best answers.