1. Home
  2. Explore
  3. Computer Science
  4. Data Structures Fundamentals

Study methods

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

Data Structures Fundamentals

Study Notes: Core Data Structures and Their Algorithms

1. Data Structures and Abstract Data Types

What a data structure is

A data structure is a way of organizing data so that it can be used efficiently. Its organization affects how quickly a program can access, search, add, remove, or update information.

Data structures matter because they:

  • Support fast and powerful algorithms.

  • Organize information in ways that match the problem being solved.

  • Make code easier to understand and maintain.

  • Can determine whether a program performs well enough to be practical.

Choosing an appropriate structure is therefore an important part of algorithm design.

Abstract data types and implementations

An abstract data type (ADT) specifies the behavior and operations that a data structure must provide, without specifying how those operations are implemented or what programming language is used.

For example, a list ADT may specify operations such as adding, removing, and accessing elements by index. Different data structures can implement that same interface:

  • A dynamic array can implement a list.

  • A linked list can also implement a list.

The two implementations provide similar behavior but have different internal organizations and performance characteristics.

A useful analogy is transportation between two locations. “Travel from point A to point B” describes a goal or interface; walking, cycling, or taking a train are different ways to implement it. Likewise, an ADT describes what a structure should do, while an implementation describes how it does it.

Other ADTs also admit multiple implementations. A queue, for example, can be implemented using a linked list, an array, or even stacks. An implementation need not be the most efficient possible one to satisfy the ADT; it must provide the required behavior.

An ADT defines the operations and behavior available to a user. A data structure is a concrete organization of data that implements that behavior.


2. Computational Complexity and Big O

Time and space complexity

Algorithm analysis commonly asks two questions:

  • Time complexity: How does the amount of work grow as the input gets larger?

  • Space complexity: How does the amount of memory used grow as the input gets larger?

An algorithm that takes impractically long to finish is not useful. Nor is one that requires an impractically large amount of memory. Complexity analysis gives a standard way to describe these requirements.

Big O notation

Big O notation describes an asymptotic upper bound on how an algorithm’s resource use grows. In typical algorithm analysis, it is used to describe worst-case performance: the input arrangement that causes the greatest amount of work or space use.

For example, searching an unsorted list of nnn distinct elements for a value may require checking every element. If the target is last, or absent, the search takes O(n)O(n)O(n) time.

Big O focuses on what happens as the input size becomes very large. It therefore ignores constant additions and constant multiplicative factors. For instance, an operation taking 3n+103n + 103n+10 steps is described as O(n)O(n)O(n) because its growth is dominated by nnn.

This is an asymptotic simplification, not a claim that constants are irrelevant in practice. A very large constant can still have a substantial real-world effect.

Common growth rates

Let nnn denote the input size.

  • Constant: O(1)O(1)O(1). The work does not grow with nnn.

  • Logarithmic: O(log⁡n)O(\log n)O(logn). The work grows slowly as nnn increases.

  • Linear: O(n)O(n)O(n). The work grows in proportion to the input size.

  • Quadratic: O(n2)O(n^2)O(n2). The work often comes from two nested loops that each perform work proportional to nnn.

  • Cubic: O(n3)O(n^3)O(n3).

  • Exponential: For example, O(2n)O(2^n)O(2n).

  • Factorial: O(n!)O(n!)O(n!).

Other growth rates are possible, such as O(n)O(\sqrt{n})O(n​), O(log⁡log⁡n)O(\log\log n)O(loglogn), or O(n5)O(n^5)O(n5). Big O can describe many mathematical functions of nnn.

Analyzing loops

A loop whose number of iterations does not depend on nnn runs in constant time, assuming each iteration performs a constant amount of work. For example, a loop that always runs 404040 times is O(1)O(1)O(1).

A loop that runs once for each of nnn input elements is linear, or O(n)O(n)O(n). A loop that increments its counter by 333 still runs in O(n)O(n)O(n) time: it may perform about n3\frac{n}{3}3n​ iterations, but the factor 13\frac{1}{3}31​ is ignored asymptotically.

For nested loops, work at different nesting levels is multiplied. Work from separate loops at the same level is added. For example, an outer loop running nnn times with two inner loops doing 3n3n3n and 2n2n2n work per outer iteration performs approximately

n(3n+2n)=5n2n(3n + 2n) = 5n^2n(3n+2n)=5n2

work, which is O(n2)O(n^2)O(n2).

If an outer loop runs 3n3n3n times and an inner loop runs about n32\frac{n^3}{2}2n3​ times, the total work is proportional to n4n^4n4, so the complexity is O(n4)O(n^4)O(n4).

Summing loop iterations

Some nested loops do not perform the same amount of work on every iteration. If the inner loop performs nnn, then n−1n-1n−1, then n−2n-2n−2, and so on iterations, the total is

n+(n−1)+(n−2)+⋯+1=n(n+1)2n + (n-1) + (n-2) + \cdots + 1 = \frac{n(n+1)}{2}n+(n−1)+(n−2)+⋯+1=2n(n+1)​

This grows quadratically, so the complexity is O(n2)O(n^2)O(n2).

Binary search

Binary search finds an item in a sorted array by repeatedly discarding half of the remaining search range:

  1. Start with a low and a high boundary.

  2. Examine the midpoint.

  3. Stop if the midpoint contains the target.

  4. Otherwise, keep the half that could still contain the target.

  5. Repeat until the range is empty or the target is found.

Because the remaining range is approximately halved each time, binary search takes O(log⁡n)O(\log n)O(logn) time in the worst case. It requires the data to be sorted.

Classic complexity examples

  • Finding all subsets of a set takes O(2n)O(2^n)O(2n) time because a set of nnn elements has 2n2^n2n subsets.

  • Finding all permutations of a string takes O(n!)O(n!)O(n!) time.

  • Merge sort takes O(nlog⁡n)O(n\log n)O(nlogn) time.

  • Visiting every cell in an nnn-by-mmm array takes O(nm)O(nm)O(nm) time.


3. Arrays

Static arrays

A static array is a fixed-length container whose elements can be accessed by index. In a zero-based array of length nnn, valid indices range from 000 through n−1n-1n−1.

Being indexable means that an element can be referenced by its numeric position. For example, the expression A[0]A[0]A[0] refers to the first element of array AAA.

Array elements are stored in a contiguous region of memory. This makes it possible to calculate an element’s location directly from its index.

Array indexing is usually zero-based in programming, unlike the one-based indexing often used in mathematics. An attempt to access an index outside the valid range, such as index nnn in an array of length nnn, is out of bounds. Many languages report this as an error; some lower-level languages may not reliably do so.

Common uses of arrays

Arrays are used widely because they provide direct indexing and form building blocks for other structures. Common uses include:

  • Temporarily storing collections of objects.

  • Acting as buffers for reading or writing data in manageable chunks.

  • Implementing lookup tables when a key can be translated into an index.

  • Returning multiple values from a function by returning a reference to an array.

  • Storing previously computed results in dynamic programming, such as in knapsack or coin-change problems.

An array can also be traversed with a “for each” loop, where the programming language handles index progression internally.

Array operations and complexity

For a static array:

  • Access or update by index: O(1)O(1)O(1).

  • Search for an arbitrary value: O(n)O(n)O(n) in the worst case.

  • Growing or shrinking the array: Not supported directly, because its length is fixed.

Inserting into a static array is possible only if the array has room and the implementation shifts elements as needed. A static array itself cannot grow to make room.

Dynamic arrays

A dynamic array behaves like an array from the user’s perspective but can grow or shrink as needed. It commonly uses a static array internally, along with two pieces of information:

  • Length: The number of elements the user currently considers part of the array.

  • Capacity: The number of positions available in the underlying storage.

The capacity may exceed the length. Unused positions are kept internal and are not treated as array elements.

When a dynamic array runs out of capacity, it:

  1. Allocates a larger static array, commonly one with twice the capacity.

  2. Copies the existing elements into it.

  3. Adds the new element.

  4. Replaces the old storage with the new storage.

For example, an array with capacity 222 can store two elements. When a third is added, the capacity can be doubled, the first two elements copied, and the third inserted.

Dynamic-array operations

  • Access or update by index: O(1)O(1)O(1).

  • Search: O(n)O(n)O(n) in the worst case.

  • Appending: Amortized O(1)O(1)O(1). Most appends are constant time; occasional resizing costs O(n)O(n)O(n), but resizing is infrequent when capacity grows geometrically.

  • Insertion in the middle: O(n)O(n)O(n) in the worst case because elements may need to shift, and resizing may also be required.

  • Deletion: Usually O(n)O(n)O(n) because later elements may need to shift left.

“Amortized O(1)O(1)O(1)” means that the average cost per append over a long sequence of operations is constant, even though an individual resize can be expensive.


4. Linked Lists

Basic structure

A linked list is a sequential collection of nodes. Each node stores data and one or more links, also called references or pointers, to other nodes.

A linked list usually maintains:

  • A head reference to the first node, which provides a starting point for traversal.

  • A tail reference to the last node.

  • The nodes themselves, which contain the data and links.

In a singly linked list, the final node’s next reference is null, indicating that there are no further nodes.

Linked-list nodes are commonly represented by classes or structures in a programming language.

Singly and doubly linked lists

  • Singly linked list: Each node points to the next node.

  • Doubly linked list: Each node points to both the next and previous nodes.

A singly linked list uses less memory because each node stores only one link. A doubly linked list uses more memory but supports movement in both directions and makes some removals easier.

Common uses

Linked lists are used to implement list-like collections, stacks, and queues. They also appear in:

  • Circular lists, where the last node points back to the first, useful for repeating cycles or round-robin processing.

  • Models of chained objects, such as train cars.

  • Separate chaining in hash tables.

  • Adjacency lists in graph representations.

Insertion

To insert a node into the middle of a singly linked list:

  1. Traverse to the node just before the insertion point.

  2. Set the new node’s next reference to the node that used to follow the predecessor.

  3. Set the predecessor’s next reference to the new node.

For a doubly linked list, both forward and backward links must be updated. Inserting between two nodes generally requires updating four references:

  • The new node’s next reference.

  • The new node’s previous reference.

  • The following node’s previous reference.

  • The preceding node’s next reference.

Removal

In a singly linked list, removing a middle node requires access to its predecessor so that the predecessor can skip over the removed node. Traversal often uses two references: one to the current node and one to the node before it.

In a doubly linked list, if a reference to the node to remove is already available, its neighboring nodes can be connected directly: the previous node points forward to the next, and the next node points backward to the previous. The removed node can then be released.

In languages that require explicit memory management, removed nodes must be deallocated to prevent memory leaks. In garbage-collected languages, removing all references allows the garbage collector to reclaim the node.

Complexity

  • Search: O(n)O(n)O(n) in the worst case.

  • Insert at the head: O(1)O(1)O(1) when the head is maintained.

  • Insert at the tail: O(1)O(1)O(1) when the tail is maintained.

  • Remove the head: O(1)O(1)O(1).

  • Remove the tail of a singly linked list: O(n)O(n)O(n), because the new tail’s predecessor must be found.

  • Remove the tail of a doubly linked list: O(1)O(1)O(1) when the tail is maintained, because its previous node is directly accessible.

  • Insert or remove at an arbitrary position: Typically O(n)O(n)O(n) when traversal is needed. Once the relevant node or neighbors are already known, pointer changes themselves take constant time.


5. Stacks

Definition and behavior

A stack is a one-ended linear data structure with two primary operations:

  • Push: Add an element to the top.

  • Pop: Remove the top element.

A stack follows last in, first out (LIFO) order: the last element added is the first one removed. A stack provides access only to its top element; other elements cannot be accessed directly through the stack interface.

A peek operation reads the top element without removing it.

Uses of stacks

Stacks appear in many programming and modeling tasks:

  • Text editors and browser navigation.

  • Checking whether brackets or braces are correctly matched.

  • Managing function calls and recursion.

  • Implementing depth-first search.

  • Modeling real-world piles of items.

  • Games such as the Tower of Hanoi, where a disc can be taken from the top of a pile and moved to another pile.

A program’s call stack keeps track of active function calls. When a function returns, its current stack frame is removed, and execution resumes in the calling function.

Matching brackets with a stack

A stack can determine whether a string of parentheses, square brackets, and curly brackets is properly matched.

Process the string from left to right:

  1. For each opening bracket, push it onto the stack.

  2. For each closing bracket, check that the stack is not empty.

  3. Pop the top opening bracket and check that it matches the closing bracket’s type.

  4. If any closing bracket has no matching opener, or has the wrong type, the sequence is invalid.

  5. After processing the whole string, the stack must be empty. If opening brackets remain, the sequence is invalid.

The final emptiness check matters because a string may end with unmatched opening brackets.

Implementing a stack

A stack can be implemented using an array or a linked list. With a singly linked list, a convenient approach is to use the head as the top:

  • Push by inserting at the head.

  • Pop by removing the head and advancing the head reference.

This makes both operations constant time. Memory must be handled correctly when nodes are removed.

Complexity

For a linked-list-based stack:

  • Push: O(1)O(1)O(1).

  • Pop: O(1)O(1)O(1).

  • Peek: O(1)O(1)O(1).

  • Search: O(n)O(n)O(n) in the worst case.


6. Queues and Breadth-First Search

Queue behavior

A queue is a linear data structure that models a line. It has two ends:

  • Elements are added at the back.

  • Elements are removed from the front.

Adding an element is called enqueueing or offering. Removing the front element is called dequeuing or polling. Peeking reads the front element without removing it.

A queue follows first-in, first-out order: the earliest element added is the earliest one removed.

Uses of queues

Queues are useful whenever items should be handled in arrival order. Examples include:

  • Modeling people waiting in line.

  • Holding the most recent xxx items in a stream by removing older items when the queue grows beyond the desired size.

  • Scheduling web-server requests that cannot all be processed simultaneously.

  • Performing breadth-first search on graphs.

Breadth-first search

Breadth-first search (BFS) visits a starting node’s neighbors first, then the neighbors of those nodes, and continues outward in layers. It can be viewed as expanding a frontier one step at a time.

A queue supports BFS:

  1. Add the starting node to the queue and mark it visited.

  2. While the queue is not empty, remove its front node.

  3. For each unvisited neighbor of that node, mark the neighbor visited and add it to the queue.

  4. Continue until the queue is empty.

Marking a node when it is enqueued prevents it from being added repeatedly.

BFS visits nodes reachable from the starting node. An isolated or disconnected node will not be visited unless the search is started from that node or another start is used.

Queue complexity and implementation

With a linked list that maintains both head and tail references:

  • Enqueue at the tail: O(1)O(1)O(1).

  • Dequeue from the head: O(1)O(1)O(1).

  • Peek at the front: O(1)O(1)O(1).

  • Search or remove an arbitrary internal element: O(n)O(n)O(n) in the worst case.

A queue can also use an array. A circular-array implementation can wrap indices from the end back to the beginning of the array, avoiding the need to shift elements after each dequeue. If the maximum queue size is known in advance, a fixed-size array can be especially efficient.


7. Priority Queues and Binary Heaps

Priority-queue behavior

A priority queue is an ADT in which each element has a priority. The element with the highest priority is removed first. The meaning of “highest” depends on the ordering convention:

  • In a min-priority queue, the smallest value has the highest priority.

  • In a max-priority queue, the largest value has the highest priority.

Elements must be comparable so that their relative priority can be determined.

A poll operation removes the current highest-priority element. It does not guarantee that repeatedly inserting and polling arbitrary values will leave the remaining elements sorted at every point; it guarantees only that each polled element is the highest-priority element currently present.

Uses

Priority queues are useful when a program must repeatedly select the next best or worst item. Examples include:

  • Dijkstra’s shortest-path algorithm.

  • Prim’s minimum spanning tree algorithm.

  • Huffman encoding for lossless compression.

  • Best-first search algorithms.

Heaps

A heap is a tree-based structure that satisfies the heap invariant:

  • 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 its children.

A heap must be a tree. It does not have to be binary in every possible implementation, but a binary heap gives each node at most two children.

A priority queue is not itself a heap. The priority queue is an ADT; a heap is one possible implementation. Other structures can implement the same behavior, though they may have different performance.

Binary heaps stored in arrays

A binary heap is commonly stored in an array. In a zero-based array, if a parent node is at index iii:

  • Its left child is at index 2i+12i+12i+1.

  • Its right child is at index 2i+22i+22i+2.

  • For a non-root node at index iii, its parent is at index ⌊i−12⌋\left\lfloor\frac{i-1}{2}\right\rfloor⌊2i−1​⌋.

Reading the array from left to right corresponds to visiting the tree level by level.

A binary heap is usually kept as a complete binary tree: every level except possibly the last is full, and the last level is filled from left to right. This gives a predictable insertion position at the end of the array.

Inserting into a binary heap

To insert an element:

  1. Place it at the next available position at the bottom right of the complete tree.

  2. Compare it with its parent.

  3. If the heap invariant is violated, swap the element with its parent.

  4. Continue until the invariant is restored or the element reaches the root.

This operation is called swimming, sifting up, or bubbling up. Since a complete binary tree has height O(log⁡n)O(\log n)O(logn), insertion takes O(log⁡n)O(\log n)O(logn) time.

Removing the root

Polling removes the root, which contains the highest-priority element:

  1. Save the root value.

  2. Swap it with the last element in the heap.

  3. Remove the last array element.

  4. Move the replacement element down as needed.

In a min-heap, the replacement is compared with its children and swapped with the smaller child if it is larger than that child. In a max-heap, the corresponding operation uses the larger child. The process continues until the heap invariant holds.

This is called sinking, sifting down, or bubbling down. Polling takes O(log⁡n)O(\log n)O(logn) time.

Other heap operations

  • Peek at the root: O(1)O(1)O(1).

  • Insert: O(log⁡n)O(\log n)O(logn).

  • Poll the root: O(log⁡n)O(\log n)O(logn).

  • Search for an arbitrary value: O(n)O(n)O(n) in a typical binary heap, because heap order does not fully sort the nodes.

  • Remove an arbitrary value: Usually O(n)O(n)O(n) because its position first has to be found, followed by heap repair.

A hash table that tracks value-to-index information can speed up containment checks to expected O(1)O(1)O(1) and arbitrary removals to O(log⁡n)O(\log n)O(logn), at the cost of additional memory and work maintaining the index map.

Building a heap

A heap can be built from an unordered array by a heapify procedure in O(n)O(n)O(n) time. This is faster than inserting all nnn elements one at a time, which takes O(nlog⁡n)O(n\log n)O(nlogn) in total. Repeatedly sinking nodes from the bottom portion of the tree is the key to the linear-time construction.

Converting between min- and max-priority behavior

If a priority queue’s comparison rule can be changed, reversing the ordering turns a min-priority queue into a max-priority queue or vice versa.

For numbers, another method is to negate each value before inserting it and negate it again when it is removed. This works for numeric values but is not a general solution for other data types.


8. Union-Find (Disjoint-Set Union)

Purpose and operations

The union-find structure, also called disjoint-set union, tracks elements partitioned into disjoint groups.

It supports two core operations:

  • Find: Determine which group contains a given element.

  • Union: Merge the groups containing two elements.

It can also track the number of remaining groups or components.

A common implementation maps each element to an integer in the range from 000 through n−1n-1n−1, then uses arrays to represent group relationships.

Parent-pointer representation

Each element has a parent pointer. Initially, every element is its own parent, so each begins as a separate group and is a root.

To find an element’s group, follow parent links until reaching a root, which is an element whose parent is itself.

To union two groups:

  1. Find the root of each element.

  2. If the roots are equal, the elements are already in the same group.

  3. Otherwise, make one root point to the other.

Union by size or rank usually attaches the smaller tree beneath the larger one, helping to prevent the parent chains from becoming too long.

Path compression

Path compression improves find operations. During a find operation, each node encountered along the path is made to point directly to the root. Later finds on those nodes then require far fewer steps.

When path compression is combined with union by size or rank, find and union take amortized nearly constant time, commonly described as O(α(n))O(\alpha(n))O(α(n)), where α\alphaα is the inverse Ackermann function. In practice, this grows so slowly that the operations are effectively constant time for realistic input sizes.

The initial structure can be created in O(n)O(n)O(n) time.

Kruskal’s minimum spanning tree algorithm

A minimum spanning tree connects every vertex in a connected weighted graph while minimizing the total edge weight. The tree contains no cycles. A graph may have multiple minimum spanning trees with the same total weight.

Kruskal’s algorithm uses union-find to build a minimum spanning tree:

  1. Sort edges by increasing weight.

  2. Examine edges in that order.

  3. If an edge’s endpoints are already in the same union-find group, skip it because adding it would create a cycle.

  4. Otherwise, add the edge and union the two endpoint groups.

  5. Stop when all vertices belong to one group, or when no more edges are available.

Union-find makes it efficient to determine whether the endpoints are already connected and to merge components after an edge is selected.

Other applications

Union-find is also useful for:

  • Testing whether two graph vertices are connected.

  • Grid percolation problems, where the aim is to determine whether a path connects opposite sides of a grid.

  • Some image-processing and tree problems.


9. Trees and Binary Search Trees

Tree concepts

A tree is an undirected graph with no cycles that is connected. Equivalent characterizations include:

  • A tree with nnn vertices has n−1n-1n−1 edges.

  • There is exactly one path between any two vertices.

A rooted tree has a designated root node. If no root has been specified, any node can be chosen as the root.

  • A parent is a node one step closer to the root.

  • A child is a node one step farther from the root.

  • A leaf is a node with no children.

  • A subtree is a node together with all of its descendants.

A binary tree is a tree in which each node has at most two children.

Binary search trees

A binary search tree (BST) is a binary tree satisfying an ordering invariant:

  • Values in a node’s left subtree are smaller than the node’s value.

  • Values in its right subtree are larger than the node’s value.

The values must be comparable. Implementations must also decide how to handle duplicates: reject them, ignore them, or place them consistently on one side.

The BST invariant applies to entire subtrees, not just to a node’s immediate children.

Uses

Binary trees and BSTs appear in:

  • Implementations of sets and maps.

  • Binary heaps.

  • Syntax trees used to represent and evaluate arithmetic expressions.

  • Compilers and calculators.

  • Other tree-based data structures.

Complexity

For a reasonably balanced BST, search, insertion, and deletion take O(log⁡n)O(\log n)O(logn) time on average. A basic, unbalanced BST can become a chain—for example, if increasing values are inserted in sequence. In that worst case, operations take O(n)O(n)O(n) time.


10. BST Insertion, Removal, and Traversal

Insertion

To insert a value into a BST:

  1. Start at the root.

  2. Compare the new value with the current node.

  3. Move left if the new value is smaller.

  4. Move right if the new value is larger.

  5. Repeat until reaching an empty child position.

  6. Insert the new node there.

If duplicates are not allowed and an equal value is found, the insertion can be rejected or ignored.

Insertion follows one path down the tree, so its time is proportional to the tree height. It is O(log⁡n)O(\log n)O(logn) in a balanced tree and O(n)O(n)O(n) in the worst case.

Finding a value

Search uses the same comparisons as insertion:

  • If the target equals the current node’s value, it has been found.

  • If it is smaller, search the left subtree.

  • If it is larger, search the right subtree.

  • If the search reaches an empty child position, the value is not in the tree.

Removing a value

Removal first finds the node. If the node exists, one of four structural cases applies:

  1. The node is a leaf: Remove it directly.

  2. Only the right subtree exists: Replace the node with the root of its right subtree.

  3. Only the left subtree exists: Replace the node with the root of its left subtree.

  4. Both subtrees exist: Replace the node’s value with a successor value, then remove the successor node from its original location.

For the fourth case, either of two values can serve as the successor:

  • The largest value in the left subtree.

  • The smallest value in the right subtree.

The smallest value in the right subtree is found by moving right once and then moving as far left as possible. The largest value in the left subtree is found by moving left once and then moving as far right as possible.

After copying a successor value into the node being removed, the original successor node must also be removed so that the value does not occur twice. That successor node will have at most one child, making its removal one of the simpler cases.

Tree traversals

A traversal visits every node in a chosen order.

Preorder

Preorder processes a node before its subtrees:

  1. Visit the current node.

  2. Traverse the left subtree.

  3. Traverse the right subtree.

Inorder

Inorder processes the node between its subtrees:

  1. Traverse the left subtree.

  2. Visit the current node.

  3. Traverse the right subtree.

Inorder traversal of a BST visits values in increasing order.

Postorder

Postorder processes the node after its subtrees:

  1. Traverse the left subtree.

  2. Traverse the right subtree.

  3. Visit the current node.

Level-order

Level-order visits nodes one level at a time, from top to bottom and left to right. It can be implemented as BFS using a queue:

  1. Enqueue the root.

  2. Dequeue and visit the next node.

  3. Enqueue its children.

  4. Continue until the queue is empty.

Unlike the depth-first traversals, level-order traversal is naturally implemented iteratively with a queue.


11. Tree Rotations and AVL Trees

Balanced binary search trees

A balanced binary search tree is a self-adjusting BST that keeps its height logarithmic in the number of stored nodes. This prevents the tree from degrading into a long chain and ensures logarithmic worst-case search, insertion, and deletion.

Most balanced BSTs combine:

  • A structural invariant that defines acceptable tree shapes.

  • Tree rotations that restore the invariant after changes.

Rotations

A rotation changes the shape of a subtree while preserving the BST ordering of its values.

In a right rotation around node AAA, where AAA has a left child BBB:

  • BBB takes the place of AAA.

  • AAA becomes the right child of BBB.

  • The relevant subtrees are reattached so that their values remain in BST order.

A left rotation is the symmetric operation.

If the rotated node has a parent, that parent must be updated to point to the new root of the rotated subtree. Implementations may also store parent links; in that case, all affected parent and child references must be updated consistently.

AVL-tree balance

An AVL tree is a self-balancing BST. For each node, define the balance factor as

balance factor=height of right subtree−height of left subtree\text{balance factor} = \text{height of right subtree} - \text{height of left subtree}balance factor=height of right subtree−height of left subtree

The height of a node is the number of edges on the longest path from that node to a leaf. A leaf therefore has height 000.

An AVL tree requires each node’s balance factor to be one of −1-1−1, 000, or 111. If insertion or deletion creates a balance factor of −2-2−2 or 222, rotations restore balance.

Four imbalance cases

  • Left-left: The node is left-heavy, and the left child is also left-heavy. Apply a right rotation.

  • Left-right: The node is left-heavy, but its left child is right-heavy. Apply a left rotation to the left child, then a right rotation to the original node.

  • Right-right: The node is right-heavy, and the right child is also right-heavy. Apply a left rotation.

  • Right-left: The node is right-heavy, but its right child is left-heavy. Apply a right rotation to the right child, then a left rotation to the original node.

These cases are mirror images of each other.

AVL insertion

AVL insertion first follows ordinary BST insertion. On the recursive return path:

  1. Update the height of each affected node.

  2. Recalculate its balance factor.

  3. Apply the appropriate rotation if the balance factor is outside the allowed range.

A node’s height can be calculated as one plus the greater of its two subtree heights. Empty subtrees can be treated as having height −1-1−1, which gives leaf nodes height 000.

AVL insertion, search, and deletion take O(log⁡n)O(\log n)O(logn) time.

AVL removal

AVL removal follows the same four cases as ordinary BST removal. After the node is removed and successor handling is complete, each affected ancestor is updated and rebalanced on the way back up the recursive call path.


12. Hash Tables

Purpose and key-value pairs

A hash table stores mappings from keys to values. Each key must identify a mapping uniquely within the table, but different keys may have the same value.

For example, a table could map people’s names to their favorite colors. Hash tables are also useful for tracking frequencies, such as counting how often words appear in a text.

Hash functions

A hash function maps a key to an integer, typically within a fixed range:

h(x)⟶integerh(x) \longrightarrow \text{integer}h(x)⟶integer

A hash function allows the table to use the hash value as an array index or as a starting point for probing.

A hash function may be designed for strings, integers, or more complex objects. A simple string hash, for example, could combine character codes and reduce the result modulo the table size. Hash functions need not give different outputs for every different key; collisions are expected.

Important properties include:

  • Determinism: The same key must always produce the same hash value.

  • Uniformity: Values should be spread through the table as evenly as practical, reducing collisions.

  • Consistency with equality: If two keys are equal, they must have equal hash values.

A collision occurs when two different keys hash to the same value. Since a hash function maps a large set of possible keys into a finite set of table positions, collisions cannot generally be avoided altogether.

Keys need stable hash values while they are stored. In many languages, this is why keys are expected to be immutable, or at least not changed in ways that affect equality or hashing.

Using a hash table

Conceptually, a hash table uses the hash value to find where a key belongs:

  1. Compute the key’s hash.

  2. Convert that hash into a valid table position.

  3. Store or search for the key and its value at that position.

  4. Resolve collisions if another key already occupies the position.

Hash-table insertion, search, and removal are typically expected or average O(1)O(1)O(1) when the hash function distributes keys well and the table is maintained at an appropriate size. In the worst case, many collisions can make operations O(n)O(n)O(n).

Resizing and load factor

The load factor is the number of stored items divided by the table capacity:

α=number of stored itemstable capacity\alpha = \frac{\text{number of stored items}}{\text{table capacity}}α=table capacitynumber of stored items​

As the table fills, collisions tend to become more frequent. Implementations therefore resize the table when the load factor exceeds a chosen threshold.

Resizing usually involves allocating a larger table and reinserting or rehashing the existing items, since their new positions depend on the new capacity.


13. Hash-Table Collision Resolution

Separate chaining

Separate chaining gives each table position a secondary collection, called a bucket, to hold all entries that hash to that position. A linked list is common, though an array, tree, or another structure can also be used.

To insert an entry:

  1. Hash the key to find its bucket.

  2. Search the bucket for the key.

  3. If the key is already there, update its value if appropriate.

  4. Otherwise, add a new key-value entry to the bucket.

To search or remove an entry, hash its key and then search or modify the corresponding bucket.

Storing both the key and value in each entry is essential. Two different keys can collide, even if they have identical or different values.

Separate chaining can tolerate a load factor greater than 111, because a bucket can hold multiple entries. However, long chains increase the work required to search a bucket. The expected performance depends on how evenly keys are distributed and on the table’s load factor.

Open addressing

In open addressing, key-value entries are stored directly in the table array. On a collision, the implementation follows a probing sequence to search for another position.

If the table capacity is nnn, a probe position can be expressed in the general form

(h(k)+p(x)) mod n\bigl(h(k) + p(x)\bigr) \bmod n(h(k)+p(x))modn

where h(k)h(k)h(k) is the key’s initial hash position, p(x)p(x)p(x) is the probing offset, and xxx counts probing attempts.

The table must keep enough unused positions that insertion can find an open slot. Open-addressing implementations therefore usually resize before the table becomes too full.

A major issue is that some probing sequences cycle through only a subset of the table. If all positions in that cycle are occupied, insertion can fail to find an open slot even though other table positions are empty. The probing rule and table capacity must therefore be chosen together.

Linear probing

Linear probing checks positions at a regular linear offset, commonly one position farther on each attempt:

p(x)=ax+bp(x) = ax + bp(x)=ax+b

The constant bbb usually only shifts the starting pattern. For a table of size nnn, the step size aaa should be relatively prime to nnn, meaning

gcd⁡(a,n)=1\gcd(a,n)=1gcd(a,n)=1

This ensures that the probe sequence can visit every position before repeating. A common choice is a step size of 111, which works for any table size.

A disadvantage of linear probing is clustering: occupied regions tend to grow together, causing later searches and insertions to require longer probe sequences.

Quadratic probing

Quadratic probing uses a quadratic offset such as

p(x)=ax2+bx+cp(x) = ax^2 + bx + cp(x)=ax2+bx+c

Not every choice of constants and table capacity visits every table position. A poorly chosen combination can produce short cycles and leave some positions unreachable.

One useful scheme uses

p(x)=x2+x2p(x) = \frac{x^2+x}{2}p(x)=2x2+x​

with a table capacity that is a power of two. Other valid schemes use different restrictions, such as prime table sizes and limits on the load factor. The important principle is that the probing formula and capacity must be chosen as a compatible pair.

Double hashing

Double hashing uses a second hash function to determine the probe step:

p(x)=x h2(k)p(x) = x\,h_2(k)p(x)=xh2​(k)

The first hash function determines the initial position; the second determines how far to move on subsequent attempts. Both functions must accept the same key type.

A zero step would repeatedly inspect the same location, so implementations must prevent the second hash from producing an unusable step. One strategy is to use a prime table size and ensure the step is nonzero and relatively prime to that size.

Double hashing often spreads probe sequences better than simple linear probing, but it still requires careful handling of table size and step values.

Deletion and tombstones

In open addressing, simply clearing a deleted slot to “empty” can break searches. A later key may have been inserted farther along the same probe sequence; a search that encounters an empty slot would stop too soon and incorrectly conclude that the key is absent.

The usual solution is a tombstone, a marker meaning “an item was removed here.” Searches continue past tombstones but stop at a genuinely empty position. Insertions may reuse tombstone positions.

Tombstones can accumulate and make searches slower. Resizing and rehashing removes them. Some implementations also use lazy relocation: if a search passes a tombstone and eventually finds the desired key, it moves the key into the earlier tombstone position to shorten future searches.


14. Fenwick Trees

Motivation

A Fenwick tree, also called a binary indexed tree, supports efficient range-sum queries and point updates on an array.

A direct range-sum query may scan every value in the requested interval, taking O(n)O(n)O(n) time in the worst case. Prefix sums can make range queries O(1)O(1)O(1), but changing a single array value may require recomputing many prefix sums.

A Fenwick tree balances these needs:

  • Construction: O(n)O(n)O(n) with a linear-time build.

  • Point update: O(log⁡n)O(\log n)O(logn).

  • Prefix or range-sum query: O(log⁡n)O(\log n)O(logn).

The structure does not add or remove array positions; it operates on a fixed-size collection of values.

One-based indexing and ranges

Fenwick trees are conventionally one-based. Each internal position stores information about a range of positions, rather than only the value at that exact position.

For a positive index iii, define its least significant set bit by

LSB⁡(i)=i&(−i)\operatorname{LSB}(i) = i \mathbin{\&} (-i)LSB(i)=i&(−i)

The least significant set bit determines the size of the range represented by that position.

For example, an index whose binary representation ends in one zero has a least significant set bit of 222 and represents a range of two positions. An index ending in two zeros has a least significant set bit of 444 and represents a range of four positions.

Prefix-sum queries

To calculate the prefix sum from index 111 through iii:

  1. Add the Fenwick-tree value at index iii.

  2. Replace iii with i−LSB⁡(i)i-\operatorname{LSB}(i)i−LSB(i).

  3. Repeat until i=0i=0i=0.

This repeatedly moves to the next lower range needed for the prefix sum.

For example, a query at index 777 uses the stored values at indices 777, 666, and 444, because successive subtraction of the least significant set bit reaches zero.

To find the inclusive sum from index lll through index rrr, subtract two prefix sums:

sum⁡(l,r)=prefix⁡(r)−prefix⁡(l−1)\operatorname{sum}(l,r) = \operatorname{prefix}(r) - \operatorname{prefix}(l-1)sum(l,r)=prefix(r)−prefix(l−1)

Point updates

To add a value xxx at position iii:

  1. Add xxx to the Fenwick-tree position iii.

  2. Move to i+LSB⁡(i)i+\operatorname{LSB}(i)i+LSB(i).

  3. Continue updating positions while they remain within the tree.

These are the positions whose stored ranges include the updated array element.

To set an array position to a specific value, an implementation can calculate the difference between the desired value and the current value, then apply that difference as a point update.

Linear-time construction

A Fenwick tree can be built from an array in O(n)O(n)O(n) time rather than applying nnn separate point updates, which would take O(nlog⁡n)O(n\log n)O(nlogn).

The linear method starts with the values in the tree array and propagates each value to its immediate parent. For a one-based index iii, that parent is

i+LSB⁡(i)i+\operatorname{LSB}(i)i+LSB(i)

If the parent is within the tree, the value at iii is added to the parent. Processing the positions in order builds the required range totals.


15. Suffix Arrays and Longest Common Prefixes

Suffixes and suffix arrays

A suffix is a nonempty substring that begins at a position in a string and continues to the end of the string. A string of length nnn has nnn suffixes.

A suffix array stores the starting indices of all suffixes, sorted in lexicographic order. It usually does not store the full suffix strings; the original string and the sorted starting indices are enough to identify them. This gives a compact representation.

Suffix arrays are space-efficient alternatives to suffix trees for many string-processing tasks. With suitable auxiliary information, such as an LCP array, they can support many of the same kinds of operations.

Longest common prefix array

An LCP array records the length of the longest common prefix shared by adjacent suffixes in suffix-array order.

If two adjacent sorted suffixes begin with the same first qqq characters, their LCP value is qqq. By convention, an undefined first entry is often set to zero.

The LCP array provides information about repeated text without storing every substring explicitly.

Counting distinct substrings

A string of length nnn has

n(n+1)2\frac{n(n+1)}{2}2n(n+1)​

substring occurrences when substrings are counted by their starting and ending positions.

The LCP array can be used to count distinct substrings. Each LCP value accounts for repeated prefixes shared by adjacent suffixes, so the number of distinct substrings is

n(n+1)2−∑iLCP⁡[i]\frac{n(n+1)}{2} - \sum_i \operatorname{LCP}[i]2n(n+1)​−∑i​LCP[i]

This avoids generating every substring and storing them in a set.

Longest repeated substring

The longest repeated substring is the longest substring that occurs at least twice. In suffix-array terms, it is found by taking the largest LCP value among adjacent suffixes.

If several suffix pairs share the maximum LCP value, there can be multiple longest repeated substrings. A positive LCP value guarantees that the corresponding prefix occurs at different positions in the original string.

Longest common substring across multiple strings

The longest common substring problem asks for the longest contiguous substring shared by multiple strings. With suffix arrays, the method can be extended to find a substring shared by at least kkk strings.

A general approach is:

  1. Concatenate the strings into one larger text.

  2. Place a distinct sentinel character between each pair of strings.

  3. Ensure sentinel characters sort before ordinary characters.

  4. Build a suffix array and LCP array for the combined text.

  5. Label each suffix by the original string from which it came.

  6. Search for a window of suffixes containing at least kkk different labels.

  7. For each valid window, use the minimum relevant LCP value in the window as the length shared by the suffixes.

  8. Keep the longest candidate found.

The sentinels prevent suffixes from extending across the boundary between two original strings and make it possible to distinguish their origins.

A sliding window can find the relevant groups of suffixes. When the window has fewer than kkk distinct source strings, it expands. When it has at least kkk, it can be tested and then shrunk. A hash table can track how many suffixes of each source string are currently in the window. A range-minimum data structure, such as a segment tree, can query the minimum LCP value for a window.

With an efficient suffix-array construction and suitable window and range-query operations, the method can run in time proportional to the total input length, up to the costs of the chosen auxiliary structures.


16. Indexed Priority Queues

Purpose

An indexed priority queue extends an ordinary priority queue by storing key-value pairs and supporting efficient updates and removals by key.

In a regular heap-based priority queue, finding an arbitrary value’s position usually requires a linear scan. An indexed priority queue maintains mappings that allow the position of a key to be found quickly, making updates and deletions logarithmic rather than linear.

This is useful when priorities can change over time—for example, when a hospital must reprioritize waiting patients or when a graph algorithm updates tentative distances.

Keys and key indices

Each key is associated with a unique key index, usually an integer in the range from 000 through n−1n-1n−1. A key may be a name or another object; a bidirectional mapping can translate between the external key and its integer index. Sometimes the keys are already suitable integers, so no extra mapping is necessary.

An indexed priority queue commonly maintains:

  • Values array: Stores the value associated with each key index.

  • Position map: Maps a key index to its current heap position.

  • Inverse map: Maps a heap position back to its key index.

  • Heap: Stores the key indices in priority order.

Using the common names pm and im, the mappings are

pm⁡[k]=heap position of key index k\operatorname{pm}[k] = \text{heap position of key index } kpm[k]=heap position of key index k

and

im⁡[i]=key index stored at heap position i\operatorname{im}[i] = \text{key index stored at heap position } iim[i]=key index stored at heap position i

The values array is indexed by key index, not by heap position.

Operations and complexity

With a binary-heap implementation:

  • Find the value for a key: O(1)O(1)O(1) after obtaining its key index.

  • Check whether a key is present: O(1)O(1)O(1).

  • Find the key or value with highest priority: O(1)O(1)O(1).

  • Insert a key-value pair: O(log⁡n)O(\log n)O(logn).

  • Poll the highest-priority pair: O(log⁡n)O(\log n)O(logn).

  • Remove a specified key: O(log⁡n)O(\log n)O(logn).

  • Update a specified key’s value: O(log⁡n)O(\log n)O(logn).

Insertion, removal, and update require moving heap entries and restoring the heap invariant. Whenever two heap positions are swapped, the position map and inverse map must be updated to stay consistent. The values array usually does not need to move because it is indexed by key index.

Insertion and removal

To insert a key-value pair:

  1. Store the value at the key’s key-index position.

  2. Place the key index at the end of the heap.

  3. Update the position and inverse maps.

  4. Swim the key index upward until heap order is restored.

To remove the highest-priority entry:

  1. Save the root key and value.

  2. Swap the root with the last heap entry.

  3. Remove the last entry.

  4. Update the maps and clear the removed key’s position.

  5. Sink or swim the replacement entry as needed.

To remove a specified key, use the position map to locate it in constant time, swap it with the last heap entry, remove it, then restore heap order.

Updating priorities

For a general update, the new value may need to move either upward or downward in the heap. The implementation can try both directions, or compare with the old value to determine which direction is needed.

For a min-heap:

  • Decreasing a key’s value makes it more competitive, so it may need to swim upward.

  • Increasing a key’s value makes it less competitive, so it may need to sink downward.

Specialized increase-key and decrease-key operations can reject changes that go in the wrong direction. These operations are useful when an algorithm requires priorities to change monotonically in a particular way.


17. Key Relationships to Remember

  • An ADT specifies behavior; a data structure provides a concrete implementation.

  • Arrays provide direct indexing; linked lists provide flexible node connections but require traversal to reach distant elements.

  • Stacks are LIFO; queues are FIFO.

  • BFS uses a queue; depth-first search can use a stack or recursion.

  • A priority queue describes priority-based behavior; a heap is a common way to implement it.

  • A heap orders parents relative to children but does not fully sort all elements.

  • A BST’s performance depends on its height; balanced BSTs maintain logarithmic height.

  • Tree rotations change shape while preserving BST order.

  • A hash table’s performance depends on stable keys, good hashing, and suitable collision resolution.

  • A Fenwick tree supports efficient prefix and range sums alongside point updates.

  • A suffix array orders suffixes, while an LCP array records shared prefixes between adjacent suffixes.

  • Union-find supports efficient connectivity checks and component merging.

  • An indexed priority queue adds efficient key-based updates and removals to the usual priority-queue operations.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent