Elementary Data Structures

Algorithms · Advanced Placement

Elementary Data Structures: the big picture

A stack supports insertion and deletion at one end only, giving last-in first-out behaviour, and is implemented either on an array with a top index or as a singly linked list; it is what maintains the call frames of a recursive program and what evaluates postfix expressions and matches brackets. A queue supports insertion at one end and deletion at the other, giving first-in first-out behaviour, and a circular buffer implements it on a fixed array without shifting elements. A linked list stores each element with a pointer to its successor, and optionally to its predecessor in the doubly linked case, which allows insertion and deletion in constant time given a pointer to the position but requires linear time to find that position; a sentinel node removes the special cases at the ends and makes the code noticeably simpler and less error-prone. Arrays give constant-time access by index and excellent cache behaviour but linear-time insertion in the middle, so the choice between array and list depends entirely on the operation mix. Rooted trees are represented by parent pointers, by child arrays, or by the left-child right-sibling scheme that handles unbounded branching in constant space per node. Dynamic arrays double their capacity when full, giving amortised constant-time append.

Stacks, Queues, Linked Lists & Dynamic Arrays

Stacks and queues differ only in which end you remove from, and that single difference determines what they are good for: a stack reverses order, which is why it runs recursion and matches brackets, while a queue preserves it, which is why it drives breadth-first search. Linked lists give constant-time insertion once you have a pointer to the position, but finding the position is linear and the pointer chasing destroys cache locality. Dynamic arrays append in amortised constant time by doubling, which is why they are the default sequence type in most languages.

{{illustration:algos-l09-f1}}

{{illustration:algos-l09-f2}}

Key relations

- Amortised append cost. ∑ᵢ₌₀^(lceil log₂ n rceil) 2ⁱ < 2n ⇒ amortised O(1)

Hash Tables, Collision Resolution & Load Factor

A hash table gives expected constant-time lookup by computing an index from the key rather than searching for it. The whole design problem is collisions, since two keys will land in the same slot. Chaining puts colliding keys in a list per slot and degrades gracefully; open addressing probes for the next free slot and is more cache-friendly but degrades sharply as the table fills. The load factor governs performance in both cases, which is why tables resize, and a poor hash function or an adversarial key set collapses the expected bound to linear.

{{illustration:algos-l09-f3}}

{{illustration:algos-l09-f4}}

Key relations

- Hash table expected costs. α = n/m ; E[probes]_chain = 1 + α ; E[probes]ₒₚₑₙ = 1/(1 − α)