Data Structures Fundamentals


Data Structures Fundamentals

Corey
Let’s build from the ground up. A data structure is a way of organizing data so it can be used efficiently—accessed, searched, or updated. The right organization can make an algorithm faster, make data feel more natural to manage, and make the code cleaner and easier to understand.

Maria
So choosing a data structure is not just an implementation detail. It can affect whether a program is merely adequate or performs well, and whether the code is understandable. A strong programmer learns not only what structures exist, but when each one fits the task.

Corey
That brings us to an important distinction: an abstract data type, or ADT, describes behavior and an interface, not a particular implementation. Think of a transportation ADT as the idea of getting from point A to point B. Walking, biking, or taking a train are different implementations of that idea.

Maria
Likewise, a list ADT says what operations a list supports—such as adding, removing, and accessing elements—but does not prescribe how to implement them. A dynamic array and a linked list can both implement a list, even though their internal structures and performance differ.

Corey
Queues and maps are also ADTs, and they can have different implementations. You can even implement a queue using stacks, though that may not be the most efficient choice. The key point is that an ADT specifies what something does; a data structure specifies how it does it.

Maria
To compare those implementations, we use computational complexity. Programmers repeatedly ask two questions: how much time will an algorithm take, and how much memory will it need? An algorithm that takes an impractical amount of time is useless, and so is one that needs an impractical amount of space.

Corey
Big O is a standard way to describe an algorithm’s growth, focusing on the worst case and on what happens as the input size gets very large. For a search through an unordered list of n items, the target might be last—or absent—so we may inspect every item. That gives linear time, O(n).

Maria
And because Big O describes growth, constant factors and lower-order terms are usually dropped. For example, seven log n cubed plus fifteen n squared plus two n cubed plus eight is O(n cubed): the cubic term dominates for large n. In practice, though, a huge constant can still matter.

Corey
The common growth rates include constant O(1), logarithmic O(log n), linear O(n), quadratic O(n squared), cubic O(n cubed), exponential such as O(2 to the n), and factorial O(n!). Expressions such as square root of n or n to the fifth can appear too. Here, n ordinarily means the input size.

Maria
A loop does not automatically mean linear time. A fixed number of operations is O(1), and a loop that always runs, say, forty times is also O(1) with respect to n. A loop from zero to n is O(n); stepping by three still gives O(n), because n divided by three has the same asymptotic growth.

Corey
Nested loops often multiply their work. One n-iteration loop inside another gives O(n squared). If the inner loop’s remaining work is n, then n minus one, then n minus two, and so on, the total is n plus n minus one plus n minus two, down to zero. That sum is n times n plus one over two, still O(n squared).

Maria
For loops at the same level that do separate work, we add the costs; for nested levels, we multiply. So an outer loop doing n iterations with inner loops doing three n and two n operations gives five n squared total, or O(n squared). If the outer loop runs three n times and an inner loop runs about n cubed times, the dominant growth is O(n to the fourth).

Corey
Binary search is a classic logarithmic algorithm. It checks a midpoint, then discards half the remaining sorted array. In the worst case, the search range is halved repeatedly, so the number of iterations grows like log base two of n.

Maria
Some useful reference points: generating all subsets of an n-element set takes O(2 to the n) possibilities, generating all permutations of a string takes O(n!), and merge sort takes O(n log n). Visiting every cell in an n-by-m array takes O(nm).

Corey
Now let’s put those ideas into the first major structure: arrays. A static array is a fixed-length container whose elements are indexable, usually from zero through n minus one. Indexable means a numeric position identifies a slot, and the slots occupy a contiguous chunk of memory.

Maria
Arrays are everywhere: they temporarily store objects, buffer chunks of a large file or an input stream, and act as lookup tables when a known offset identifies the data. They can also hold multiple return values when a language normally allows just one, and they are used in dynamic programming to cache computed subproblems.

Corey
Because an array is indexable, reading or setting an element by index takes O(1) time. Searching for a value can take O(n), because the value may be missing and every element may need checking. Indexing is typically zero-based in computer science: the first element is at index zero, not one.

Maria
A dynamic array keeps the convenient indexing of an array but can grow and shrink. A common implementation stores elements in a larger static array, tracks the number actually in use, and resizes when capacity is exhausted. When it runs out of room, it allocates a larger array—often double the capacity—copies the elements, and adds the new one.

Corey
That resize makes a particular append expensive, since copying may take O(n) time. But resizing happens only occasionally, so appending is amortized O(1): averaged across many appends, the cost per append stays constant. Inserting or deleting in the middle can be O(n) because elements may need to shift and be copied.

Maria
A linked list organizes data differently. It is a sequence of nodes, each holding data and a reference to another node. We keep a reference to the head so we have a place to begin traversing, and we call the final node the tail. In a singly linked list, each node points forward; in a doubly linked list, it also points backward.

Corey
The extra backward reference costs memory—each pointer itself takes space—but makes some operations easier. A singly linked list uses less memory, but finding a previous node means traversing from the head. With a doubly linked list, a reference to a node gives access to both neighbors, so removing that known node can be done in constant time by reconnecting them.

Maria
Searching a linked list is O(n). Adding or removing at the head is O(1), and adding at the tail can be O(1) when a tail reference is maintained. Removing the tail from a singly linked list is O(n), because we must find the node before it; a doubly linked list can move the tail backward in O(1). Inserting or removing by position still requires finding that position, so it is generally linear.

Corey
Linked lists are useful implementations of lists, stacks, and queues. Circular linked lists connect the tail back to the head, which can model repeating cycles or round-robin order. Linked lists also appear in hash-table separate chaining and graph adjacency lists.

Maria
A stack is a one-ended structure with two central operations: push and pop. Both add and remove at the top, so it follows LIFO—last in, first out. If you push an apple, then an onion, the onion is the first one popped.

Corey
Stacks show up in browser navigation, text editing, matching braces in compilers, and the Tower of Hanoi. They also support recursion: function calls are placed on a call stack, and returning from a function removes its stack frame. Depth-first graph search can use a stack explicitly or use recursion.

Maria
With a linked-list implementation, a stack can push and pop at the head in O(1), and peeking at the top is O(1). Searching for an arbitrary value is O(n). If an operation tries to pop or peek an empty stack, it must handle that case rather than pretending an element exists.

Corey
A queue models a line. It has a front and a back: enqueue—or offer—adds at the back, while dequeue—or poll—removes from the front. That is FIFO, first in, first out. Peeking examines the front without removing it.

Maria
Queues model real waiting lines, retain only the most recent fixed number of items, and manage requests waiting for a server. If a server can handle only a few requests at once, extra requests can wait in a queue and be processed as capacity becomes available.

Corey
Enqueue, dequeue, and peeking can be O(1) with an appropriate implementation, such as a linked list with head and tail references. Searching for an item, or removing an arbitrary item from inside the queue, can take O(n). A queue is also central to breadth-first search.

Maria
Breadth-first search explores a graph outward from a starting node: first its neighbors, then the neighbors of those nodes, and so on. A queue holds the frontier. Mark the start as visited and enqueue it; repeatedly dequeue a node, then enqueue each unvisited neighbor and mark that neighbor visited.

Corey
That visits reachable nodes in breadth-first order. It does not magically reach disconnected parts of a graph: an isolated node remains unvisited if there is no path to it from the start. An array-based queue can also be efficient when a maximum size is known; a circular arrangement lets its front and back wrap around the array.

Maria
A priority queue is another ADT, but unlike a regular queue, each element has a priority. The element with the highest priority comes out first. Priorities require comparable values, so the elements need an ordering. A min-priority queue returns the smallest value first; a max-priority queue returns the largest.

Corey
A priority queue does not have to be a heap. It could be implemented with another structure, such as an unordered list, but a heap is a common choice because it supports the key operations efficiently. A heap is a tree that satisfies a heap invariant: each parent is ordered relative to its children.

Maria
In a min-heap, each parent is less than or equal to its children; in a max-heap, each parent is greater than or equal to them. The heap must also be a tree. A binary heap has up to two children per node, but heaps can have other branching structures too.

Corey
A binary heap is often stored in an array. For a zero-based array, the children of the node at index i are at indices two i plus one and two i plus two. The complete-tree shape keeps the insertion position predictable: add at the end, then swim or bubble the new value upward until the heap invariant holds.

Maria
To remove the root, swap it with the last element, remove the last slot, and sink or bubble the replacement downward until the invariant is restored. Peeking at the root is O(1); adding and polling are O(log n), because a node may move along the height of the tree. Building a heap from an unordered array can be done in O(n) time.

Corey
Removing an arbitrary heap element is different: without extra bookkeeping, we must first search for it, which can take O(n), then restore the heap. A hash table mapping values to their positions can make locating an element faster, though maintaining that map adds memory and work, especially when elements move.

Maria
Priority queues are valuable when we repeatedly need the next best or worst candidate. They appear in Dijkstra’s shortest-path algorithm, Prim’s minimum-spanning-tree algorithm, Huffman coding, and best-first search. If a library offers the opposite ordering from the one you need, you can reverse the comparison; for numbers, negating on insertion and negating again when retrieving is one workaround.

Corey
An indexed priority queue extends the idea by storing key–value pairs and supporting quick updates or deletion by key. Think of a hospital waiting room: patients have priorities, but their conditions can change, and someone can leave the queue. We need to update or remove a particular patient without scanning the whole heap.

Maria
The indexed version assigns each key a unique key index, often from zero to n minus one. It maintains a values array, a position map telling where each key index sits in the heap, and an inverse map telling which key index sits at each heap position. Swapping heap nodes updates the maps, so a key’s node can be found quickly.

Corey
With those maps, lookup, update, and deletion by key can avoid the linear search needed by an ordinary heap. Heap rearrangement still takes O(log n), while the mapping lets us locate the node efficiently. Specialized increase-key or decrease-key operations check that the proposed change goes in the intended direction before updating.

Maria
For graph algorithms, that distinction matters: a candidate’s priority can improve or worsen while the algorithm runs. An indexed priority queue lets us revise its value directly, rather than inserting duplicates and searching for the old entry.

Corey
Next is union-find, also called the disjoint-set structure. It tracks elements partitioned into disjoint groups. Its two essential operations are find, which identifies an element’s group, and union, which merges two groups. Imagine magnets joining into clusters: find tells us which cluster a magnet belongs to; union combines clusters.

Maria
Union-find is useful for connectivity questions, such as whether two graph vertices are connected, and for grid percolation. It is especially clear in Kruskal’s minimum-spanning-tree algorithm. Sort edges by weight, then consider them from lightest to heaviest: add an edge if its endpoints are in different groups, and union those groups. Skip it if the endpoints already share a group, because that would create a cycle.

Corey
A simple implementation maps elements to integer indices and stores each index’s parent in an array. Initially, each element is its own parent and therefore its own group. To find a group, follow parent links until reaching a root that points to itself. To union two groups, find both roots and make one root point to the other.

Maria
That basic approach can create long chains. Path compression improves it: during find, after discovering the root, make the nodes along the route point directly to that root. Union by size—attaching the smaller group beneath the larger—also helps keep the trees shallow. With these optimizations, find and union are amortized almost-constant-time operations; the number of groups can be tracked directly.

Corey
Now let’s move from lists and heaps to trees. A tree is a connected, acyclic graph; equivalently, a tree with n nodes has n minus one edges. If we choose a root, nodes below another node are its children, and the node above is its parent. A leaf has no children, and a subtree is a node together with the tree below it.

Maria
A binary tree gives each node at most two children. A binary search tree adds an ordering rule: values in a node’s left subtree are smaller, and values in its right subtree are larger, subject to whatever duplicate-value convention the implementation chooses. The values must be comparable so insertion can decide which way to go.

Corey
To insert, begin at the root, compare the new value with the current node, and continue left or right until reaching an empty position. Searching follows the same comparisons. When the tree is reasonably balanced, these operations are O(log n) on average. But a sequence such as increasing values can produce a chain, making operations O(n) in the worst case.

Maria
Removing from a binary search tree has a find phase and a replacement phase. A leaf can simply be removed. If the node has just one child, its child takes its place. If it has two children, replace its value with either the largest value in the left subtree or the smallest in the right subtree, then remove that successor node.

Corey
Tree traversals give different visiting orders. Preorder processes the current node before its recursive visits to the left and right subtrees. Inorder visits left, then current, then right. Postorder visits both subtrees first and processes the current node last.

Maria
For a binary search tree, inorder traversal visits values in increasing order. Level-order traversal instead visits one level at a time. It is breadth-first search on the tree, so an iterative implementation uses a queue: dequeue a node, process it, and enqueue its children.

Corey
Balanced binary search trees prevent the chain-shaped worst case by adjusting themselves so their height stays logarithmic. Many use rotations. A right rotation moves a node’s left child up and the original node down to become that child’s right child; a left rotation is the mirror image.

Maria
A rotation changes the shape without breaking the binary-search ordering, provided the subtrees are reattached correctly. Implementations must update the relevant child links—and parent links if nodes store them. That makes rotations easy to get wrong, but they are the basic tool for restoring balance.

Corey
An AVL tree is a balanced binary search tree that tracks each node’s balance factor, defined here as right-subtree height minus left-subtree height. The tree requires each factor to be minus one, zero, or plus one. If insertion makes a factor plus two or minus two, rotations restore the rule.

Maria
There are four imbalance patterns: left-left is fixed with a right rotation; right-right with a left rotation. Left-right needs a left rotation on the left child, then a right rotation on the unbalanced node. Right-left is the mirror: rotate right on the right child, then left on the unbalanced node.

Corey
After an AVL insertion, update the node heights and balance factors as recursion returns, then rebalance where needed. Removal follows the same basic find-and-replace cases as in a regular binary search tree, but the tree also needs its height and balance information updated and may need rotations on the way back up.

Maria
Hash tables map keys to values using a hash function that maps a key to an integer used to select a table position. Keys need to be hashable, and the hash must be deterministic: the same key must always produce the same hash. Keys also generally need to be immutable so their hash does not change while stored.

Corey
Different keys can produce the same hash; that is a collision, not proof that the keys are equal. Equal hash values mean the keys might match, so compare the keys themselves to confirm. A good hash function spreads keys fairly uniformly, reducing collisions. With a suitable table and hashing strategy, insertion, lookup, and removal are average O(1), though poor distribution can make them O(n).

Maria
One collision strategy is separate chaining. Each table position, or bucket, holds a secondary structure—often a linked list—containing all entries that hash there. To look up a key, hash it to a bucket, then search that bucket. When the table gets too full, implementations can resize it and reinsert the entries.

Corey
The other major strategy is open addressing: store entries directly in one array and probe for another position after a collision. The load factor is the number of stored items divided by table capacity. As it grows, finding a free position becomes harder, so the table is resized before it gets too full.

Maria
Linear probing checks successive positions; quadratic probing uses a quadratic offset; double hashing uses a second hash function to determine the offset. The probing sequence must be chosen carefully. Some choices cycle through only part of the table, which can cause an infinite search even when another slot is free.

Corey
That is why implementations pair a probing rule with suitable table-size conditions. Linear probing commonly uses a step that can reach every position, while quadratic probing and double hashing have their own constraints. When resizing, entries have to be rehashed for the new table; simply copying them to their old positions is not enough.

Maria
Deletion in open addressing has a subtle trap. If you replace a removed entry with an empty slot, a later search might stop there and incorrectly conclude that a key farther along the probe sequence is absent. So deletion leaves a tombstone instead: searches skip it, and a later insertion may reuse it. Resizing can clean out accumulated tombstones.

Corey
A Fenwick tree, also called a binary indexed tree, supports prefix-sum and range-sum queries on an array, along with point updates. A plain scan can answer a range sum in O(n). Prefix sums make queries O(1), but changing one array value can force many prefix sums to be recomputed.

Maria
Fenwick trees balance those costs. They use a one-based array in which each cell stores information for a range of positions determined by its least significant set bit. To compute a prefix sum, start at the requested index and repeatedly subtract that least significant bit until reaching zero, adding the values encountered.

Corey
A range sum from i through j can be obtained by subtracting the prefix sum before i from the prefix sum through j. For a point update, add the change at the target index and repeatedly add the least significant bit to reach each responsible cell. These operations take O(log n) time.

Maria
You can construct a Fenwick tree by applying point updates to every value in O(n log n), but there is a linear-time construction. Copy the values into the one-based structure and propagate each cell’s accumulated value to its immediate parent, at index i plus the least significant bit of i, when that parent is in range.

Corey
For string processing, a suffix is a nonempty substring that runs from some position to the end of the string. A suffix array stores the starting indices of all suffixes in sorted order. It need not store the suffix strings themselves, because the original string plus those indices identifies them.

Maria
The longest common prefix array, or LCP array, records how many initial characters two neighboring sorted suffixes share. By convention, the first entry is often zero. Together, the suffix array and LCP array support useful string tasks without storing every suffix separately.

Corey
For example, the number of distinct substrings can be found from the total number of substrings, n times n plus one divided by two, minus the repeated-prefix contributions recorded by the LCP array. The sum of the LCP values counts those repeated substrings, so subtracting it leaves the unique ones.

Maria
The longest repeated substring is even simpler once the arrays are built: find the maximum LCP value. Neighboring sorted suffixes with a large common prefix share a long substring that occurs at different positions. If several LCP entries tie for the maximum, there may be several longest repeated substrings.

Corey
Suffix arrays also help with the longest common substring shared by at least k of several strings. Concatenate the strings with distinct separator characters that sort before the ordinary characters, then build the suffix array and LCP array. Label each suffix by the source string it came from.

Maria
Now use a sliding window of suffixes that contains at least k different source strings. For each valid window, the minimum relevant LCP value gives a common-prefix length shared across the selected suffixes. Track the best length and corresponding substring, expanding the window when it lacks a needed string and shrinking it when it already qualifies.

Corey
The window can move across the suffix array in linear progress, while a range-minimum structure or a sliding-window minimum method can help find the minimum LCP efficiently. The broader lesson is that suffix arrays and LCP information turn many string problems into organized comparisons among sorted suffixes.

Maria
So we have a toolkit, not a single best structure: arrays give fast indexing; linked lists give flexible links; stacks and queues enforce different processing orders; heaps prioritize; union-find tracks groups; search trees organize ordered values; hash tables map keys; Fenwick trees answer cumulative queries; and suffix arrays expose substring structure.

Corey
And the through-line is to match the structure to the operations you need. Start with the ADT behavior, understand the implementation choices, and compare their time and space costs—especially in the worst case and as the input grows. That foundation makes it much easier to choose well in real algorithms.

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