1. Home
  2. Explore
  3. Computer Science
  4. CS50 Data Structures Overview

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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 size counter 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)O(1)O(1)) and efficient for binary search (O(log⁥n)O(\log n)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)O(n)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 next pointer is NULL for the last node.

  • An extra pointer called list or head points to the first node; initially NULL.

Visual representation:

list → [1|•] → [2|•] → [3|NULL]
  • Each box is a node; the dot represents the next pointer; arrows show links.

Three Insertion Strategies

  1. Prepend (constant time O(1)O(1)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.

  2. Append (linear time O(n)O(n)O(n)) – add new node at the end:

    • First traverse the entire list to find the last node, then set its next to the new node.

    • Requires a loop to reach the end; cost grows with list size.

  3. Sorted insertion (linear time O(n)O(n)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->next is NULL or ptr->next->number > new number, then splice in.

Searching a Linked List

  • Linear search: start at head, follow next pointers until the target is found or NULL is reached.

  • Running time: O(n)O(n)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(1)O(1)

O(n)O(n)O(n)

Insertion (prepend)

O(n)O(n)O(n) (copy)

O(1)O(1)O(1)

Insertion (append/sorted)

O(n)O(n)O(n) (copy)

O(n)O(n)O(n) (traverse)

Search

O(log⁥n)O(\log n)O(logn) (if sorted)

O(n)O(n)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   7
  • This is a balanced BST: height = 333, n=7n = 7n=7, search cost = O(log⁥n)O(\log n)O(logn).

Searching a BST

Recursive algorithm:

  • Base case: if tree is NULL, return false.

  • 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(log⁥n)O(\log n)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
     \
      4
  • Searching becomes O(n)O(n)O(n) because there is no branching.

  • Self‑balancing trees (e.g., AVL, red‑black) are used in practice to maintain O(log⁥n)O(\log n)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 mmm, 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 next pointer.

[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][0, m-1][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)O(1)O(1) – every key has a unique bucket (ideal hash function, no collisions).

  • Average case: O(1+Îą)O(1 + \alpha)O(1+Îą) where Îą=n/m\alpha = n/mÎą=n/m is the load factor. With a good hash and enough buckets, Îą\alphaÎą is small.

  • Worst case: O(n)O(n)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 NULL pointers.

  • To insert a word like "TOAD":

    1. Start at root.

    2. Use first letter 'T' → follow children[19] (assuming A=0). If NULL, allocate a new node.

    3. Move to that node. Use second letter 'O' → follow children[14]. Allocate if needed.

    4. Continue for 'A' and 'D'. At the final node, store the value (e.g., phone number) in the number field.

  • 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‑NULL value, the word exists.

  • Number of steps = length of the word (a constant, e.g., ≤ 30 for most names). This is O(k)O(k)O(k) where kkk is the maximum key length, effectively O(1)O(1)O(1).

Running Time

  • Search: O(k)O(k)O(k) = O(1)O(1)O(1) (constant per operation, independent of the total number of keys nnn).

  • Insert: O(k)O(k)O(k) = O(1)O(1)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)O(1)O(1) prepend insertion but lose binary search.

  • Binary search trees offer O(log⁥n)O(\log n)O(logn) search if kept balanced; unbalanced trees degrade to O(n)O(n)O(n).

  • Hash tables provide near‑constant average‑time operations using buckets and linked lists; worst case is O(n)O(n)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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent