Lesson 8 · Foundations

Introduction to Data Structures

A data structure is a way of arranging values in memory so that some operations are cheap. Choosing one means deciding which operations your program runs most.

Introduction to Data Structures concept diagramA visual explanation of the layout and operations shown in this lesson.the same four values, arranged three waysArraycontiguous slotsLinked listnodes and referencesHash mapkey to bucket10203040index → O(1)insert middle → O(n)10203040index → O(n)insert at node → O(1)kjlookup by key → O(1) avgorder → not keptpick the layout whose cheap operation is the one you do mostevery structure trades one operation against another — none is best at everything
1

What a Data Structure Is

A data structure is a way of organising values in memory together with the operations that organisation makes efficient. The second half matters most: you choose a structure for what it makes cheap, not for how it stores things.

Every structure is a trade. An array reads any position in O(1) but inserting in the middle costs O(n). A hash table finds a key in O(1) on average but keeps no order. A balanced search tree keeps keys sorted at O(log n) per operation. No structure is fast at everything, so the useful question is never "which is best?" but "which operations does this program run most often?"

  • Layout plus the operations it makes efficient
  • Every structure speeds up some operations by slowing others
  • Ask what the program does most, not what is best in general
2

Types of Data Structures

The usual classification splits types of data structures in three ways. Primitive types (integers, floats, characters, booleans) hold one value; non-primitive structures hold many and are built from primitives.

Non-primitive structures are then divided into linear and non linear data structures. In a linear structure each element has at most one predecessor and one successor: arrays, linked lists, stacks and queues. In a non-linear structure an element can connect to several others: trees branch into a hierarchy and graphs allow any connection. The split predicts how you walk them: a loop for linear ones, recursion or an explicit stack or queue for the rest.

Structures are also static or dynamic. A static structure has a size fixed when it is created, like a plain array; a dynamic one grows and shrinks as you insert and delete, like a linked list or a resizable array.

  • Primitive: one value; non-primitive: many
  • Linear: one sequence; non-linear: hierarchy or network
  • Static: fixed size; dynamic: grows and shrinks
3

Data Structure Operations

  1. Traverse: visit every element once, in some defined order
  2. Search: find an element by value or key
  3. Insert: add an element and keep the structure's rules intact
  4. Delete: remove an element and repair what it held together
  5. Access and update: read or change an element by index, key or reference
  6. Sort and merge: order the elements, or combine two structures into one

Whatever the structure, the same handful of data structure operations come up, and comparing structures means comparing what each of these costs.

Insert and delete have two costs: finding the place, and the work the change triggers, such as shifting array elements, rebalancing a tree, or resizing a hash table. A linked list inserts in O(1) only if you already hold the node; finding it first is O(n).

  • Cost each operation separately
  • Count the finding step as well as the change itself
  • Watch for hidden work: shifting, rebalancing, resizing
Key reference

Terms, operations, and practical uses

Core vocabulary

  • ElementOne stored value or record.
  • KeyThe identifier used to find a record without relying on its numeric position.
  • InvariantA condition the representation must preserve after every operation.
  • Abstract data typeThe promised behavior—such as stack or queue—independent of the storage used underneath.

Operation checklist

  • AccessRead an item by index, key, or reference.
  • UpdateReplace data while preserving the structure's rules.
  • Insert and removeMeasure both the local change and any shifting, rebalancing, or rehashing it causes.
  • TraverseVisit all reachable items in a defined order.

Selection questions

  • OrderingMust records keep insertion order, sorted order, or no order at all?
  • Lookup frequencyRepeated key searches often justify a hash table or ordered index.
  • Memory layoutContiguous storage improves locality; node-based storage permits local rewiring.
Implementation

Code in Python, C++ and Java

values = [10, 20, 30, 40, 50]
target = 40

# 1. Unsorted array: check every element. O(n)
def linear_search(data, x):
    for i, v in enumerate(data):
        comparisons = i + 1
        if v == x:
            return i, comparisons
    return -1, len(data)

# 2. Sorted array: discard half each step. O(log n)
def binary_search(data, x):
    lo, hi, comparisons = 0, len(data) - 1, 0
    while lo <= hi:
        mid = (lo + hi) // 2
        comparisons += 1
        if data[mid] == x:
            return mid, comparisons
        if data[mid] < x:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1, comparisons

# 3. Hash map: jump straight to the slot. O(1) average
lookup = {v: i for i, v in enumerate(values)}

_, a = linear_search(values, target)
_, b = binary_search(values, target)
c = 1 if target in lookup else 0

print(f"Unsorted array {a} comparisons · sorted array {b} · hash map {c}")
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

// 1. Unsorted array: check every element. O(n)
int linearSearch(const vector<int>& data, int x, int& comparisons) {
    for (int i = 0; i < (int)data.size(); i++) {
        comparisons = i + 1;
        if (data[i] == x) return i;
    }
    comparisons = (int)data.size();
    return -1;
}

// 2. Sorted array: discard half each step. O(log n)
int binarySearch(const vector<int>& data, int x, int& comparisons) {
    int lo = 0, hi = (int)data.size() - 1;
    comparisons = 0;
    while (lo <= hi) {
        int mid = (lo + hi) / 2;
        comparisons++;
        if (data[mid] == x) return mid;
        if (data[mid] < x) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

int main() {
    vector<int> values = {10, 20, 30, 40, 50};
    int target = 40, a = 0, b = 0;

    // 3. Hash map: jump straight to the slot. O(1) average
    unordered_map<int, int> lookup;
    for (int i = 0; i < (int)values.size(); i++) lookup[values[i]] = i;

    linearSearch(values, target, a);
    binarySearch(values, target, b);
    int c = lookup.count(target) ? 1 : 0;

    cout << "Unsorted array " << a << " comparisons · sorted array " << b
         << " · hash map " << c << '\n';
}
import java.util.HashMap;
import java.util.Map;

class Main {
    static int comparisons = 0;

    // 1. Unsorted array: check every element. O(n)
    static int linearSearch(int[] data, int x) {
        for (int i = 0; i < data.length; i++) {
            comparisons = i + 1;
            if (data[i] == x) return i;
        }
        comparisons = data.length;
        return -1;
    }

    // 2. Sorted array: discard half each step. O(log n)
    static int binarySearch(int[] data, int x) {
        int lo = 0, hi = data.length - 1;
        comparisons = 0;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;
            comparisons++;
            if (data[mid] == x) return mid;
            if (data[mid] < x) lo = mid + 1;
            else hi = mid - 1;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] values = {10, 20, 30, 40, 50};
        int target = 40;

        // 3. Hash map: jump straight to the slot. O(1) average
        Map<Integer, Integer> lookup = new HashMap<>();
        for (int i = 0; i < values.length; i++) lookup.put(values[i], i);

        linearSearch(values, target);
        int a = comparisons;
        binarySearch(values, target);
        int b = comparisons;
        int c = lookup.containsKey(target) ? 1 : 0;

        System.out.println("Unsorted array " + a + " comparisons · sorted array " + b
            + " · hash map " + c);
    }
}
Watch it run

Step through it

Running on Ann 40, Bo 75, Cy 60, Di 90 · update(Bo, 95), top(), score(Cy)

the taskplayers in arrival orderAnn 40[0]Bo 75[1]Cy 60[2]Di 90[3]cells read per operationupdate(Bo, 95)top()score(Cy)unsorted arraysorted arrayhash map
Step 1

One leaderboard, three operations

Four players and three things the program must do: raise Bo's score to 95, report the top player, and look up Cy's score. The same data will be stored three ways, and each way will run all three operations. The grid records how many cells each one has to read.

Output
1 / 11
4

Abstract Data Type vs Data Structure

An abstract data type is a promise about behaviour: which operations exist and what they guarantee, with nothing said about memory. "push adds an item, pop removes the most recently pushed one" fully defines a stack ADT. A data structure is the concrete arrangement that keeps that promise.

One ADT can have several implementations with different costs. A stack can sit on an array or a linked list. A map can be a hash table (O(1) average lookup, no order) or a balanced tree (O(log n), sorted iteration). Library names follow the ADT, not the layout: Python's list is a dynamic array, not a linked list, and Java's HashMap and TreeMap share the Map interface with very different structures underneath.

  • ADT: the operations and what they promise
  • Data structure: the memory layout that keeps the promise
  • Check which structure a library type really uses
5

The Structures Worth Knowing First

A short list covers most real programs. Each lesson linked in the table goes into the layout, the operations and their costs; here the point is what each one is for.

Stacks and queues are not new layouts. They are restrictions on an array or list, and their value is in what they forbid: a stack only lets you touch the most recent item, which is exactly what undo, recursion and bracket matching need.

What each structure makes cheap, and what it gives up
StructureCheapCostlyReach for it when
Dynamic arrayIndex access, iteration, appendInsert or delete in the middleYou need an ordered sequence; the default
Linked listInsert or delete at a node you holdAccess by indexEdits dominate and you keep node references
Stack / queuePush and pop at the endsAnything in the middleProcessing order is the requirement
Hash tableLookup, insert, delete by keyOrdered iterationYou ask "have I seen this?"
Balanced search treeOrdered and range queriesLarger constant factorsSorted order must be kept up to date
HeapReading the min or maxSearching for anything elseYou repeatedly need the extreme value
GraphModelling any relationshipNothing is O(1) by defaultThings connect many-to-many
  • Dynamic array is the default sequence
  • Hash table for membership and lookup by key
  • Balanced trees keep order; hash tables give it up
6

Choosing One

  1. List the operations and how often each runs; the one in the inner loop decides
  2. Does order matter? Sorted output or range queries rule out a plain hash table
  3. Where do inserts and deletes happen? Only at the ends suggests a stack, queue or deque
  4. Check what big-O hides: memory per node, worst-case pauses from resizing, disk access

Under exam or interview pressure, the same four questions settle most choices. The tracer below runs them on a leaderboard.

When two structures tie on big-O, prefer the one with better cache locality. Scanning a contiguous array is several times faster than following pointers through the same number of nodes, which is why array-backed structures often win in practice. Big-O describes growth, not speed; measure when it is close.

  • The inner-loop operation decides
  • Order requirements rule hash tables out
  • On a tie, take the better memory layout