Programming Search⌘K

Conceptintro

Data structure

Also called data structures, concrete data structure, representation, contiguous structure, linked structure.

A data structure is a way to lay out data in memory so that some operations are fast. Arrays, linked lists, hash tables and trees store the same elements at different costs.

Applies to
core-languages

Idea

The same five numbers can sit in memory in more than one way. An array puts them side by side, so the program finds the fourth number by arithmetic on its address. A linked list puts each number in its own node with a pointer to the next node, so the program must follow three pointers to reach the fourth number. But the linked list can add a number at the front without moving the others. A data structure is such a layout, together with the code that keeps it in order.

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next


array = [10, 20, 30, 40, 50]
linked = None
for v in reversed(array):
    linked = Node(v, linked)


def linked_get(head, i):
    steps = 0
    while i > 0:
        head, i, steps = head.next, i - 1, steps + 1
    return head.value, steps


print("array:", array[3], "after 0 pointer steps")
print("linked:", *linked_get(linked, 3), "pointer steps")

linked = Node(5, linked)  # add at the front: no element moves
array.insert(0, 5)        # add at the front: every element moves one place
print(linked.value, array)
Output
array: 40 after 0 pointer steps
linked: 40 3 pointer steps
5 [5, 10, 20, 30, 40, 50]

Both hold the same values and both answer "get element 3" and "add at the front". The cost of each answer differs. Reading by position is fast in the array and slow in the linked list. Adding at the front is the other way round.

How it works

A layout for some operations. NIST defines a data structure as "An organization of information, usually in memory, for better algorithm efficiency"1. Wikipedia says it is "a way to organize and store data that is usually chosen for efficient access to data"2. No layout is fast for every operation, so the choice of a data structure is a choice of which operations to make cheap.

Contiguous and linked. Most data structures are built from two methods. In the first, "arrays and records store elements in contiguous memory locations, requiring a rigid layout but allowing fast indexed access by computing the address through arithmetic operations"2. In the second, "linked data structures (such as linked lists and trees) store addresses of related elements within their structure, enabling flexible memory usage and dynamic resizing"2. A hash table combines them: it keeps an array of slots, and it uses "a hashing function to map keys to indexes in an array, allowing for constant-time access in the average case"2.

Rules that the code keeps. "Most data structures have associated algorithms to perform operations, such as search, insert, or balance, that maintain the properties of the data structure"1. A sorted array stays sorted after each insert. A balanced tree rotates its nodes so that no path becomes too long. A data structure "may include redundant information, such as length of the list or number of nodes in a subtree"1, and each operation must keep that information correct.

The structure behind a collection. A collection or an abstract data type says which operations exist. The data structure is how they are done. "There may be multiple concrete data structures for the same ADT, for example a linked list or a resizable array for the list ADT"2. Java puts the data structure in the class name: the general-purpose classes are hash tables (HashSet, HashMap), resizable arrays (ArrayList, ArrayDeque), balanced trees (TreeSet, TreeMap) and linked lists (LinkedList)3. Python does not show the structure in the name, but its documentation says it. CPython lists "are really variable-length arrays, not Lisp-style linked lists"4, and CPython dictionaries "are implemented as resizable hash tables"4.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaStandard library
CIdiom
C#Standard library
JavaScriptNative
TypeScriptNative
GoNative
RustStandard library
KotlinStandard libraryKotlin has ArrayList, ArrayDeque, HashMap and LinkedHashMap, and it can use the Java classes on the JVM. No example file exists because kotlinc is not installed.
SQLDoes not applyThe database chooses how to store a table, and a query does not name a data structure.
BashIdiom
PowerShellStandard libraryPowerShell has arrays and hash tables, and it can use the .NET classes such as a LinkedList. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no data structures in program code.
CSSDoes not applyCSS has no data structures in program code.
Regular expressionsDoes not applyA regular expression does not store data.
Language Verdict Mechanism
Python native list is a dynamic array, dict and set are hash tables; collections.deque and heapq for others; classes for custom structures
JavaScript native Array, Map, Set and typed arrays; objects and classes for custom structures
TypeScript native the JavaScript structures; classes and interfaces with item types for custom structures
Java stdlib ArrayList, LinkedList, ArrayDeque, HashMap, TreeMap, PriorityQueue; classes for custom structures
Kotlin stdlib ArrayList, ArrayDeque, HashMap, LinkedHashMap; the Java classes on the JVM
C# stdlib List<T>, LinkedList<T>, Dictionary<TKey,TValue>, SortedDictionary<TKey,TValue>, PriorityQueue<TElement,TPriority>
Go native arrays, slices and maps in the language; structs and pointers for custom structures
Rust stdlib Vec, VecDeque, LinkedList, HashMap, BTreeMap, BinaryHeap; structs, enums and Box for custom structures
C idiom arrays, structs and pointers; each structure is written by hand or taken from a library
C++ stdlib std::vector, std::deque, std::list, std::unordered_map, std::map, std::priority_queue
Bash idiom indexed and associative arrays; other structures are built from arrays of indices
PowerShell stdlib arrays and hash tables, and the .NET classes
SQL n/a the database chooses the storage of a table; indexes are outside the language of a query
Regex n/a a pattern does not store data
HTML n/a HTML has no data structures in program code
CSS n/a CSS has no data structures in program code

Each language has an array and a hash table that are ready to use. Java, C#, Rust and C++ add linked lists, trees and heaps in the standard library. C has only arrays, structs and pointers, so a C program builds the rest itself.

The example files build the same two structures as the idea: an array and a singly linked list of five numbers. Each one reads element 3 from both and counts the pointer steps, then adds a number at the front of the list. Python, JavaScript and TypeScript use a class for the node. Java and C# use a small class with a next field. Go and C use a struct and a pointer. Rust uses Option<Box<Node>>. C++ uses a struct with std::unique_ptr. Bash keeps the values and the next indices in two arrays.

PythonGitHub
from dataclasses import dataclass


@dataclass
class Node:
    value: int
    next: "Node | None" = None


array = [10, 20, 30, 40, 50]
head = None
for v in reversed(array):
    head = Node(v, head)


def get(node, i):
    steps = 0
    while i > 0:
        node, i, steps = node.next, i - 1, steps + 1
    return node.value, steps


print(f"array[3] = {array[3]} (0 steps)")
value, steps = get(head, 3)
print(f"linked[3] = {value} ({steps} steps)")

head = Node(5, head)
out = []
node = head
while node:
    out.append(str(node.value))
    node = node.next
print("after push_front:", " ".join(out))
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: native. A Python list is a dynamic array. A linked list is a small class whose objects hold a value and a reference to the next object.
  • Reading by index from the array takes one step. The linked list follows one reference for each position.
  • Adding at the front of the linked list makes one node and moves nothing.
#include <array>
#include <iostream>
#include <memory>

struct Node {
    int value;
    std::unique_ptr<Node> next;
};

int main() {
    std::array<int, 5> array{10, 20, 30, 40, 50};
    std::unique_ptr<Node> head;
    for (auto it = array.rbegin(); it != array.rend(); ++it) {
        head = std::make_unique<Node>(Node{*it, std::move(head)});
    }

    std::cout << "array[3] = " << array[3] << " (0 steps)\n";
    const Node* n = head.get();
    int steps = 0;
    for (int i = 3; i > 0; --i, ++steps) {
        n = n->next.get();
    }
    std::cout << "linked[3] = " << n->value << " (" << steps << " steps)\n";

    head = std::make_unique<Node>(Node{5, std::move(head)});
    std::cout << "after push_front:";
    for (const Node* m = head.get(); m != nullptr; m = m->next.get()) {
        std::cout << ' ' << m->value;
    }
    std::cout << '\n';
}
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: stdlib. The containers library has std::array, std::vector, std::deque, std::list, std::forward_list, std::map and std::unordered_map.
  • Each node owns the next one through std::unique_ptr, so the list frees itself when head goes out of scope.
JavaGitHub
import java.util.StringJoiner;

public class Main {
    record Node(int value, Node next) {}

    public static void main(String[] args) {
        int[] array = {10, 20, 30, 40, 50};
        Node head = null;
        for (int i = array.length - 1; i >= 0; i--) {
            head = new Node(array[i], head);
        }

        System.out.println("array[3] = " + array[3] + " (0 steps)");
        Node n = head;
        int steps = 0;
        for (int i = 3; i > 0; i--, steps++) {
            n = n.next();
        }
        System.out.println("linked[3] = " + n.value() + " (" + steps + " steps)");

        head = new Node(5, head);
        StringJoiner out = new StringJoiner(" ");
        for (Node m = head; m != null; m = m.next()) {
            out.add(String.valueOf(m.value()));
        }
        System.out.println("after push_front: " + out);
    }
}
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: stdlib. Java has arrays in the language, and ArrayList, LinkedList, ArrayDeque, HashMap and TreeMap in java.util.
  • The example writes its own node as a record, to show the pointer steps. In a program, use java.util.LinkedList or, more often, ArrayList.
#include <stdio.h>
#include <stdlib.h>

struct node {
    int value;
    struct node *next;
};

static struct node *push_front(struct node *head, int value) {
    struct node *n = malloc(sizeof *n);
    if (n == NULL) {
        exit(1);
    }
    n->value = value;
    n->next = head;
    return n;
}

int main(void) {
    int array[] = {10, 20, 30, 40, 50};
    struct node *head = NULL;
    for (int i = 4; i >= 0; i--) {
        head = push_front(head, array[i]);
    }

    printf("array[3] = %d (0 steps)\n", array[3]);
    struct node *n = head;
    int steps = 0;
    for (int i = 3; i > 0; i--, steps++) {
        n = n->next;
    }
    printf("linked[3] = %d (%d steps)\n", n->value, steps);

    head = push_front(head, 5);
    printf("after push_front:");
    while (head != NULL) {
        struct node *next = head->next;
        printf(" %d", head->value);
        free(head);
        head = next;
    }
    printf("\n");
    return 0;
}
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: idiom. C has arrays, structs and pointers. The program writes each other data structure itself, or uses a library.
  • array[3] is the address of array plus three times the size of an int. The linked list follows next three times.
  • Each node comes from malloc, so the program must free each one.
using System;
using System.Collections.Generic;

int[] array = { 10, 20, 30, 40, 50 };
Node? head = null;
for (int i = array.Length - 1; i >= 0; i--)
{
    head = new Node(array[i], head);
}

Console.WriteLine($"array[3] = {array[3]} (0 steps)");
Node n = head!;
int steps = 0;
for (int i = 3; i > 0; i--, steps++)
{
    n = n.Next!;
}
Console.WriteLine($"linked[3] = {n.Value} ({steps} steps)");

head = new Node(5, head);
var output = new List<string>();
for (Node? m = head; m != null; m = m.Next)
{
    output.Add(m.Value.ToString());
}
Console.WriteLine("after push_front: " + string.Join(" ", output));

record Node(int Value, Node? Next);
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: stdlib. System.Collections.Generic has List<T> (a dynamic array), LinkedList<T>, Dictionary<TKey,TValue> (a hash table) and SortedDictionary<TKey,TValue> (a tree).
  • The record Node holds a value and a reference to the next node. Node? says that the reference can be null.
JavaScriptGitHub
const array = [10, 20, 30, 40, 50];
let head = null;
for (const v of [...array].reverse()) {
  head = { value: v, next: head };
}

function get(node, i) {
  let steps = 0;
  for (; i > 0; i--, steps++) node = node.next;
  return [node.value, steps];
}

console.log(`array[3] = ${array[3]} (0 steps)`);
const [value, steps] = get(head, 3);
console.log(`linked[3] = ${value} (${steps} steps)`);

head = { value: 5, next: head };
const out = [];
for (let n = head; n; n = n.next) out.push(n.value);
console.log("after push_front:", out.join(" "));
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: native. Array, Map and Set are built in. A linked list is a chain of plain objects, each with a value and a next property.
TypeScriptGitHub
interface ListNode<T> {
  value: T;
  next: ListNode<T> | null;
}

const array: number[] = [10, 20, 30, 40, 50];
let head: ListNode<number> | null = null;
for (const v of [...array].reverse()) {
  head = { value: v, next: head };
}

function get<T>(node: ListNode<T>, i: number): [T, number] {
  let steps = 0;
  for (; i > 0; i--, steps++) node = node.next!;
  return [node.value, steps];
}

console.log(`array[3] = ${array[3]} (0 steps)`);
const [value, steps] = get(head!, 3);
console.log(`linked[3] = ${value} (${steps} steps)`);

head = { value: 5, next: head };
const out: number[] = [];
for (let n: ListNode<number> | null = head; n; n = n.next) out.push(n.value);
console.log("after push_front:", out.join(" "));
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: native. TypeScript uses the JavaScript structures. An interface with a type parameter describes the node of a linked list.
  • The type ListNode<T> | null makes the end of the list explicit, and the checker asks the code to handle it. The ! tells the checker that the node is not null.
package main

import (
	"fmt"
	"strconv"
	"strings"
)

type node struct {
	value int
	next  *node
}

func main() {
	array := [5]int{10, 20, 30, 40, 50}
	var head *node
	for i := len(array) - 1; i >= 0; i-- {
		head = &node{array[i], head}
	}

	fmt.Printf("array[3] = %d (0 steps)\n", array[3])
	n, steps := head, 0
	for i := 3; i > 0; i-- {
		n = n.next
		steps++
	}
	fmt.Printf("linked[3] = %d (%d steps)\n", n.value, steps)

	head = &node{5, head}
	var out []string
	for m := head; m != nil; m = m.next {
		out = append(out, strconv.Itoa(m.value))
	}
	fmt.Println("after push_front:", strings.Join(out, " "))
}
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: native. Arrays, slices and maps are in the language. A linked structure is a struct with a pointer field.
  • The package container/list has a doubly linked list, but most Go code uses a slice.
RustGitHub
struct Node {
    value: i32,
    next: Option<Box<Node>>,
}

fn get(mut node: &Node, mut i: usize) -> (i32, usize) {
    let mut steps = 0;
    while i > 0 {
        node = node.next.as_deref().expect("index out of range");
        i -= 1;
        steps += 1;
    }
    (node.value, steps)
}

fn main() {
    let array = [10, 20, 30, 40, 50];
    let mut head: Option<Box<Node>> = None;
    for &v in array.iter().rev() {
        head = Some(Box::new(Node { value: v, next: head }));
    }

    println!("array[3] = {} (0 steps)", array[3]);
    let (value, steps) = get(head.as_deref().unwrap(), 3);
    println!("linked[3] = {} ({} steps)", value, steps);

    head = Some(Box::new(Node { value: 5, next: head }));
    let mut out = Vec::new();
    let mut n = head.as_deref();
    while let Some(m) = n {
        out.push(m.value.to_string());
        n = m.next.as_deref();
    }
    println!("after push_front: {}", out.join(" "));
}
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: stdlib. std::collections has Vec, VecDeque, LinkedList, HashMap, BTreeMap and BinaryHeap.
  • A node owns the next node through Option<Box<Node>>. None ends the list.
BashGitHub
array=(10 20 30 40 50)

# A linked list in two arrays: value[k] and next[k]; -1 ends the list.
value=() next=()
head=-1
for (( i = ${#array[@]} - 1; i >= 0; i-- )); do
  k=${#value[@]}
  value[k]=${array[i]}
  next[k]=$head
  head=$k
done

echo "array[3] = ${array[3]} (0 steps)"
n=$head steps=0
for (( i = 3; i > 0; i-- )); do
  n=${next[n]}
  steps=$(( steps + 1 ))
done
echo "linked[3] = ${value[n]} ($steps steps)"

k=${#value[@]}
value[k]=5 next[k]=$head head=$k
out=()
for (( n = head; n != -1; n = next[n] )); do
  out+=("${value[n]}")
done
echo "after push_front: ${out[*]}"
Output
array[3] = 40 (0 steps)
linked[3] = 40 (3 steps)
after push_front: 5 10 20 30 40 50
  • Verdict: idiom. Bash has indexed and associative arrays and nothing else. A linked structure is built from arrays, with indices in place of pointers.
  • The node at index k has its value in value[k] and the index of the next node in next[k].
  • Static and dynamic. A fixed array has a size that does not change. A dynamic array moves to a bigger block when it is full. A linked structure grows one node at a time.
  • Persistent structures. Some structures keep the old version after an update, so that both versions stay valid. NIST lists the persistent data structure as one kind of data structure1.
  • The structure in the API. Java names its classes by structure, and Rust names Vec, VecDeque, HashMap and BTreeMap by structure too. Python, JavaScript and Go give one name for each kind, such as list or map, and hide the structure.

Pitfalls

  • Picking a linked list for fast inserts. A linked list inserts in O(1) only when the code already holds the node. To find the place, "Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index"5. The Rust documentation says that "Vec is generally going to be faster than VecDeque, and VecDeque is generally going to be faster than LinkedList"6 when the costs in its table are the same.
  • Code that assumes the wrong structure. An operation that is fast on one structure can be slow on another. The Python sequence mixins call __getitem__ many times. If that method "is linear (as it would be with a linked list), the mixins will have quadratic performance"7.
  • Average cost is not worst cost. A hash table is fast on average. "It is theoretically possible, though very unlikely, for HashMap to experience significantly worse performance than the expected cost"6.
  • Calling a structure by the name of a type. A stack is a type with push and pop. An array and a linked list are two structures that can give it. Choose the type first, and then the structure. See abstract data type.

Cost

The cost of an operation depends on the structure, not on the name of the collection. For a Java ArrayList, "The add operation runs in amortized constant time, that is, adding n elements requires O(n) time"8, get and set take constant time, and "All of the other operations run in linear time (roughly speaking)"8. For CPython lists, the array layout "makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index"4. The Rust table gives O(1) for get(i) on a Vec, O(min(i, n-i)) on a LinkedList, and O(log(n)) for a lookup in a BTreeMap6. Layout matters too: "the contiguous memory allocation in arrays facilitates rapid access and modification operations, leading to optimized performance in sequential data processing scenarios"2. The analysis of these costs is on the algorithm site.

History

Algorithms + Data Structures = Programs is "a 1976 book written by Niklaus Wirth"9. Its title states the idea of this page: a program is made of its algorithms and of the data structures that they work on. Wikipedia reports that Rob Pike said that the choice of data structure almost always has a greater effect on efficiency than the choice of algorithm2.

References

  1. data structure, Dictionary of Algorithms and Data Structures, NIST, Definition; Note
  2. Data structure, Wikipedia, Introduction; Usage; Implementation; Examples
  3. Collections Framework Overview, Java SE 21, Collection Implementations
  4. Design and History FAQ, Python 3.14 documentation, How are lists implemented in CPython?; How are dictionaries implemented in CPython?
  5. Class LinkedList, Java SE 21, Class description
  6. Module std::collections, Rust standard library, Performance; Cost of Collection Operations
  7. collections.abc, Python 3.14 documentation, class collections.abc.Sequence
  8. Class ArrayList, Java SE 21, Class description
  9. Algorithms + Data Structures = Programs, Wikipedia, Introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/D93GJH/text.yaml