Data Structures and Algorithms
Algorithms, Data Structures, and Computational Efficiency
Algorithms and Data Representation
An algorithm is a sequence of step-by-step instructions for solving a problem. An algorithm can be logically correct but still inefficient if it requires too much time or memory.
The efficiency of an algorithm depends on more than its instructions. It also depends on:
How data is arranged in memory
Whether the data is sorted
Whether elements are stored next to one another
How much memory the data structure requires
Whether the computer can access elements directly or must traverse them sequentially
Key idea: Algorithms and data structures work together. The same problem can be solved much more efficiently when the data is stored in an appropriate structure.
Computers ultimately store information as bits, represented by 0 and 1. These bits are grouped into larger units, commonly:
Bit: A single 0 or 1
Byte: Typically 8 bits
Memory address or index: A number identifying a location in memory
The arrangement of these bits and bytes affects how quickly a computer can find, insert, remove, or sort data.
Searching Unsorted Data
Suppose a computer must find the number 50 among seven hidden values. If the values are stored in random order, there is no reliable way to eliminate possibilities before examining them.
The computer may have to inspect:
The first value
The second value
The third value
Every subsequent value until 50 is found
If the desired value is last, all n elements may need to be examined. This is called linear search.
Linear Search
Linear search examines elements one at a time, usually from left to right.
A simplified version is:
Start with the first element.
Compare it with the target.
If it matches, stop.
Otherwise, move to the next element.
Repeat until the target is found or no elements remain.
Efficiency of Linear Search
If there are n elements:
Worst case: The target is last or absent, requiring approximately n checks.
Best case: The target is first, requiring only one check.
Worst-case upper bound: O(n)
Best-case lower bound: Ω(1)
The search cannot reliably do better on randomly ordered data because no information indicates which unexamined location is more likely to contain the target.
A computer might find the target immediately by chance, but luck is not a dependable algorithm. An algorithm must provide a repeatable procedure whose efficiency can be analyzed.
The Importance of Sorted Data
A phone book makes searching much faster because its names are arranged alphabetically. The sorting work is performed before the search begins.
The same principle can be applied to numbers:
Unsorted values provide little information about where a target might be.
Sorted values allow comparisons to eliminate large portions of the search space.
Sorting requires an upfront investment of time and possibly additional memory.
This creates an important trade-off:
Sorting takes time initially, but it can make later searches much faster.
If data will be searched repeatedly, the cost of sorting may be worthwhile.
Binary Search
Binary search is a divide-and-conquer algorithm that searches sorted data by repeatedly eliminating half of the remaining possibilities.
Binary Search Process
To search for a value in sorted data:
Examine the middle element.
If the middle element equals the target, stop.
If the target is smaller, discard the right half.
If the target is larger, discard the left half.
Repeat the same process on the remaining half.
For example, if the sorted values are:
To search for 50:
Check the middle value, 16.
Since 50>16, ignore all values to the left.
Check the middle of the remaining values, 42.
Since 50>42, check the remaining value, 50.
Find the target after three checks.
Efficiency of Binary Search
Each comparison cuts the remaining problem approximately in half:
The number of divisions required is approximately:
Therefore:
Worst-case running time: O(logn)
Best case: Ω(1), if the target is initially in the middle
Typical exact bound under appropriate conditions: Θ(logn)
Binary search is much faster than linear search for large collections. However, it depends on two major requirements:
The data must be sorted.
The computer must be able to access the middle element directly.
Contiguous Memory and Arrays
Binary search works especially well when data is stored in an array.
An array is a contiguous block of memory in which values are stored next to one another.
“Contiguous” means that the elements occupy consecutive memory locations.
For example, an array containing six values might conceptually look like this:
The elements have indexes:
4 at index 0
8 at index 1
15 at index 2
16 at index 3
23 at index 4
42 at index 5
Most programming languages use zero-based indexing, meaning that the first element is at index 0 rather than index 1.
Calculating an Array Position
If an array has seven elements, its indexes are:
The middle index can be calculated by dividing the number of elements by 2 and rounding down:
The computer can use arithmetic to calculate the address of an element. If every element occupies the same amount of memory, the address of an element can be found from:
Because the computer can calculate this address directly, accessing an array element by index takes constant time:
Why Contiguity Matters
If values are stored back-to-back, the computer knows how far apart the elements are. It can jump directly to the requested index.
If values are scattered randomly throughout memory, calculating an index does not identify the correct location. The computer would need additional information to find each element.
Random Access Memory
Random Access Memory, or RAM, consists of numbered memory locations. “Random access” means that the computer can access a particular byte directly rather than having to read every earlier byte first.
The memory locations are conceptually numbered:
The addresses are not usually stored inside the bytes themselves. They are part of the memory system’s organization and allow the computer to locate data.
Big O, Big Omega, and Big Theta
Computer scientists use mathematical notation to describe how an algorithm’s running time changes as the input size grows.
Big O: Upper Bound
Big O, written O(f(n)), describes an upper bound on an algorithm’s growth rate.
For example:
means that the running time grows linearly with the size of the input in the relevant case, often the worst case.
Common growth rates include:
O(1) — constant time
O(logn) — logarithmic time
O(n) — linear time
O(nlogn) — linearithmic time
O(n2) — quadratic time
Big Omega: Lower Bound
Big Omega, written Ω(f(n)), describes a lower bound.
For linear search:
The target might be found immediately.
Therefore, the best case can take one step.
The lower bound is:
Big Theta: Tight Bound
Big Theta, written Θ(f(n)), is used when the upper and lower bounds have the same growth rate.
If an algorithm consistently grows at the same rate in both directions, its running time can be described as:
These notations focus on growth as n becomes large. Constants and lower-order terms are usually ignored because they have less effect on large inputs.
For example:
is dominated by the n2 term as n grows. It is therefore described as:
This does not mean the algorithm takes exactly n2 steps. It means that the quadratic term determines the general growth rate.
Sorting Algorithms
Sorting rearranges data into a desired order, such as smallest to largest or alphabetically.
Sorting is useful because it can enable faster operations, especially binary search. However, sorting itself requires time and may require additional memory.
Bubble Sort
Bubble sort repeatedly compares neighboring elements and swaps them when they are out of order.
Larger values gradually move toward the end of the collection, appearing to “bubble” upward through the list. Equivalently, smaller values move toward the beginning.
Bubble Sort Process
For a list arranged from smallest to largest:
Compare the first and second elements.
If they are out of order, swap them.
Compare the second and third elements.
Continue comparing adjacent pairs.
Repeat complete passes until a pass makes no swaps.
A pass that makes no swaps proves that the entire list is sorted, because every adjacent pair is already in the correct order.
Bubble Sort Pseudocode
repeat until no swaps occur:
for i from 0 to n - 2:
if element i and element i + 1 are out of order:
swap themThe loop stops at n−2 because each comparison involves both element i and element i+1. The final valid comparison is therefore between indexes n−2 and n−1.
Local Corrections and Global Order
Each individual swap fixes only a local problem. It does not necessarily sort the entire collection.
However, repeated local improvements eventually produce a globally sorted result.
Important principle: A complex global result can sometimes be achieved by repeatedly solving small local problems.
Bubble Sort Efficiency
With n elements:
A pass compares approximately n−1 adjacent pairs.
In the worst case, approximately n passes may be needed.
This produces approximately:
comparisons, which is on the order of:
Bubble sort can stop early if the data becomes sorted before all possible passes are completed, but its worst-case behavior is quadratic.
Selection Sort
Selection sort repeatedly searches the unsorted portion for the smallest remaining element and places it in its correct position.
Selection Sort Process
Search the entire list for the smallest element.
Swap it with the first element.
Search the remaining unsorted portion for the next-smallest element.
Swap it into the second position.
Continue until all elements are placed.
For example:
First, select the smallest value and place it at index 0.
Next, select the smallest value from indexes 1 through n−1 and place it at index 1.
Continue with indexes 2, 3, and so on.
Selection Sort Pseudocode
for i from 0 to n - 1:
find the smallest element between index i and index n - 1
swap the smallest element with element iAfter each iteration, the sorted region grows by one element, while the unsorted region shrinks.
Selection Sort Efficiency
The first search examines approximately n−1 other elements. The next examines approximately n−2, then n−3, and so on.
The total number of comparisons is approximately:
This sum equals:
Expanding it:
The n2 term dominates for large values of n, so selection sort has running time:
Selection sort performs fewer swaps than bubble sort in some situations, but both have quadratic growth in their typical worst-case analysis.
Comparing Bubble Sort and Selection Sort
Bubble Sort
Compares neighboring elements
Swaps elements whenever a neighboring pair is out of order
Can stop early if a complete pass makes no swaps
Moves large elements toward the end
Has O(n2) worst-case running time
Selection Sort
Searches the remaining unsorted region
Selects the smallest element
Places it directly into its final position
Does not need to repeatedly swap every local inversion
Has O(n2) running time
Both algorithms generally perform repeated comparisons over progressively organized data. Their quadratic growth makes them inefficient for very large collections.
Time–Space Trade-Off in Sorting
An algorithm can sometimes run faster by using more memory.
Bubble sort and selection sort perform their operations largely in place, meaning they rearrange elements within the original collection and require little additional storage.
A faster algorithm may use temporary storage to hold intermediate results. This creates a trade-off:
Less memory may require more repeated work.
More memory may reduce the time required.
The best choice depends on whether time or space is more limited.
Merge Sort
Merge sort is a divide-and-conquer sorting algorithm. It divides the input into smaller portions, sorts those portions, and then merges them into a complete sorted list.
Merge Sort Process
Divide the list into two halves.
Recursively divide each half into smaller halves.
Continue until each sublist contains one element.
Treat each one-element list as already sorted.
Merge pairs of sorted sublists.
Continue merging larger sorted sections until one complete sorted list remains.
A list with one element requires no sorting because it is already ordered.
Merging Sorted Lists
Suppose two sorted lists are:
and
The merge process compares the first unused element of each list:
Compare 4 and 8; take 4.
Compare 16 and 8; take 8.
Compare 16 and 15; take 15.
Take the remaining 16.
The result is:
Because each half is already sorted, the merge can be performed efficiently.
Merge Sort Efficiency
Merge sort divides the list into levels:
One level has n elements.
The next level has two sections of approximately 2n elements.
Further levels divide the data into smaller sections.
The number of division levels is approximately log2n.
Each level processes all n elements during merging.
Therefore, merge sort has running time:
This is faster than the quadratic running time of bubble sort and selection sort for large inputs.
Merge Sort and Additional Space
Merge sort usually requires temporary storage for the intermediate sorted sections. It may use approximately twice the space of an in-place algorithm during parts of the process.
Its advantage comes from exchanging additional space for reduced time:
Bubble sort: approximately O(n2) time and little extra space
Selection sort: approximately O(n2) time and little extra space
Merge sort: approximately O(nlogn) time and additional space
Arrays and Dynamic Growth
Arrays provide fast random access because their elements are contiguous and equally spaced in memory. However, this organization creates difficulties when the array must grow.
Fixed Allocation
When a program requests memory, it typically asks the operating system for a specific amount.
Suppose six values are stored in six consecutive bytes. If the program later needs a seventh value, the next memory location may already belong to another part of the program.
The array then has two possibilities:
Reject the new value because there is no adjacent space.
Request a larger contiguous block and move all existing values into it.
Relocating an Array
If the operating system cannot extend the array in place, it may need to allocate a new region elsewhere.
The existing values must then be copied:
This relocation takes time proportional to the number of stored elements.
Arrays therefore provide:
Fast access by index
Efficient binary search when sorted
Efficient sorting operations
Efficient use of memory for the data itself
But they also have:
Limited capacity unless extra space is reserved
Potentially expensive resizing
Wasted memory if much more capacity is reserved than needed
Reserving Extra Capacity
A program might initially request more space than it currently needs, such as space for 8, 16, or 100 values.
This reduces the chance of immediate relocation, but it can waste memory:
Unused locations cannot be used by other programs.
Physical memory is finite.
Reserving too much space may reduce the resources available for other tasks.
Central trade-off: Arrays exchange flexibility for speed and direct access.
The appropriate choice depends on the relative importance of:
Time
Memory space
Hardware cost
Development complexity
Expected data growth
Linked Lists
A linked list is a dynamic data structure in which elements are stored in separate nodes connected by references to one another.
Unlike an array, a linked list does not require all elements to occupy adjacent memory locations.
Nodes and Pointers
Each linked-list node typically stores:
The actual data value
The address of the next node
The address or reference to another node is often called a pointer.
For example, a node containing 42 might also store the address of the node containing 50.
Conceptually:
The arrows represent stored addresses or pointers. A computer does not have literal arrows; it stores numerical addresses encoded as bits.
The final node indicates that there is no next node, often using a special null value or an all-zero convention.
Advantages of Linked Lists
Linked lists can grow and shrink dynamically:
New nodes can be placed wherever free memory exists.
The new node can be connected to the existing structure.
Removing a node requires updating the pointer that leads to it.
The remaining nodes do not need to be moved.
For example, to remove a node from the middle:
Identify the node before the target.
Change its pointer so that it skips the target.
The target node is no longer part of the list.
To insert a node:
Allocate a new node.
Set its pointer to the appropriate next node.
Update the previous node’s pointer to refer to the new node.
Disadvantages of Linked Lists
Linked lists lose the constant-time random access provided by arrays.
An array can calculate the location of its middle element directly. A linked list generally cannot, because its nodes may be separated by arbitrary amounts of memory.
To reach the middle of a linked list, the computer must begin at the first node and follow pointers one by one.
Therefore:
Accessing the first known node can be very fast.
Searching for an arbitrary value may require traversing the entire list.
Searching has worst-case time O(n).
Accessing the kth element generally takes O(k) time.
Linked lists also require additional memory for pointers. Instead of storing only one value per node, each node stores:
The data
The address of the next node
This pointer overhead can be significant, especially when the data values themselves are small.
Arrays provide random access but limited growth. Linked lists provide flexible growth but sequential access.
Trees and Binary Search Trees
A tree adds another dimension to the organization of linked data. Instead of each node pointing to only one successor, a node may point to multiple child nodes.
A tree consists of nodes connected in a hierarchy.
Tree Terminology
Root: The starting or top node
Parent: A node that points to one or more children
Child: A node reached from a parent
Subtree: A tree contained within a larger tree
Leaf: A node with no children
Height: The number of levels or links along a longest path
In computer science diagrams, trees are commonly drawn with the root at the top and children below it, even though natural trees are often drawn in the opposite orientation.
Binary Trees
A binary tree is a tree in which each node has no more than two children:
A left child
A right child
A node may have zero, one, or two children.
Binary Search Trees
A binary search tree is a binary tree organized according to an ordering rule:
Every value in the left subtree is less than the node’s value.
Every value in the right subtree is greater than the node’s value.
The same rule applies recursively to every node.
For example:
16
/ \
8 42
/ \ / \
4 15 23 50To search for 15:
Start at 16.
Since 15<16, move left to 8.
Since 15>8, move right to 15.
The target is found.
This search requires only a few steps rather than scanning every value.
Efficiency of a Binary Search Tree
If the tree is balanced, each comparison eliminates a large portion of the remaining possibilities. Searching and inserting can approach:
This gives a binary search tree some of the benefits of both arrays and linked lists:
Dynamic insertion and removal
Faster search than a general linked list
No requirement that all nodes be contiguous
Unbalanced Trees
A binary search tree can become badly unbalanced. If values are inserted in increasing order, the tree may become a chain:
4
\
8
\
15
\
16This structure behaves like a linked list, causing search time to degrade to:
Some tree structures automatically rebalance themselves so that their height remains small. Rebalancing requires additional logic and implementation complexity, but it helps preserve logarithmic performance.
Tree Space Requirements
Each tree node may store:
Its data
A pointer to its left child
A pointer to its right child
Thus, trees generally use more memory than arrays and may use more pointer storage than singly linked lists.
Trees trade additional memory and complexity for faster dynamic searching.
Hash Tables
A hash table combines an array with a function that maps keys to locations.
It is designed to provide very fast insertion and lookup, ideally in constant time.
Keys and Values
A hash table stores associations between:
Key: The input used to identify data
Value: The data associated with that key
For example:
Key: a person’s name
Value: a phone number
A programming-language dictionary is an example of this key–value model.
Hash Functions
A hash function converts a key into an array index.
Suppose names are stored using their first letter. The function might map:
A to index 0
B to index 1
C to index 2
D to index 3
Because computers represent characters using encodings such as ASCII or Unicode, a character can be converted to a number. For uppercase ASCII letters:
A has a numerical code of 65
B has a numerical code of 66
D has a numerical code of 68
Subtracting 65 gives:
Thus:
This involves a constant number of operations, independent of the total number of stored names.
Hash Table Lookup
To find a name:
Examine the relevant key, such as the first letter.
Apply the hash function.
Obtain an array index.
Jump directly to that index.
Search the associated location or bucket.
With a good hash function and few conflicts, lookup and insertion can approach:
Collisions
A collision occurs when multiple keys produce the same hash value.
For example, both David and Doug begin with D, so a hash function based only on the first letter maps both to the same bucket.
One way to handle collisions is to store a linked list at each array location:
D bucket → David → Doug → another D nameThe array provides fast access to the correct bucket, while the linked list stores multiple values that share the same hash.
Collision Performance
If each bucket contains only a few values, lookup remains close to constant time.
However, if many keys map to the same bucket, the linked list becomes long. In the worst case, every key may collide, producing one long linked list with linear lookup time:
A poor hash function creates too many collisions.
Improving a Hash Function
Instead of hashing only the first letter, a function might use the first two letters:
DA
DB
DC
DD
DO
This creates more buckets and distributes names more evenly. Ideally, each bucket contains very few values.
The effectiveness of a hash table depends on:
The quality of the hash function
The number of available buckets
The distribution of keys
The number of collisions
A hash table is approximately constant-time, not guaranteed constant-time in every possible input arrangement.
Common Data Types and Their Underlying Structures
High-level programming languages provide abstractions that hide the complexity of memory management.
Common types include:
Boolean: A value such as true or false
Integer: A whole number
Float: A number containing a fractional or decimal component
String: A sequence of characters
List: A dynamically growing sequence
Dictionary: A key–value structure implemented using hashing
Set: A collection that does not contain duplicates
Tuple: A grouped collection of values, such as an x,y coordinate or latitude and longitude
Range: A representation of a sequence of values
At the hardware level, all of these are ultimately represented using bits and bytes. Higher-level structures use additional rules, metadata, addresses, and pointers to make the raw memory useful.
Integers
Some languages allocate a fixed number of bytes for integers. Other languages, including modern versions of Python, allow integers to grow to accommodate increasingly large values.
Larger integers may require more memory and more operations.
Floating-Point Values
Floating-point numbers use a fixed number of bits to represent approximate real numbers.
If a float is allocated 32 or 64 bits, only a limited amount of precision is available. The available bits must encode:
The sign
The magnitude
The fractional information
Because the number of bits is finite, many decimal values cannot be represented exactly.
Strings
A string is stored as a sequence of characters, with each character represented by a numerical encoding.
A growing string may require:
Additional adjacent memory
Reallocation in a larger region
Copying existing characters to the new region
The programming language hides these operations behind the string abstraction.
Lists
A high-level list combines the conceptual behavior of an array with dynamic growth.
Depending on the language’s implementation, a list may:
Use a resizable array
Reserve extra capacity
Relocate values when capacity is exceeded
Use references or other internal structures
The important abstraction is that the programmer can add and remove elements without manually managing each memory address.
Dictionaries
A dictionary represents associations between keys and values. Internally, it is generally implemented using a hash table or a related structure.
This allows code to express relationships such as:
A name associated with a phone number
A word associated with a definition
A username associated with account information
The key is hashed to identify where the corresponding value should be stored.
Sets and Tuples
A set stores values without duplicates. Its implementation often uses hashing or another structure that allows efficient membership testing.
A tuple groups multiple related values together, such as:
or:
The choice of data structure depends on the required operations, such as:
Membership testing
Ordering
Index-based access
Dynamic growth
Uniqueness
Key–value association
Major Trade-Offs Among Data Structures
No single data structure is best for every task.
Array
Strength: Constant-time access by index, O(1)
Strength: Excellent for binary search when sorted
Weakness: Requires contiguous memory
Weakness: Resizing can require copying all elements
Weakness: Reserving excess capacity wastes memory
Linked List
Strength: Grows and shrinks dynamically
Strength: Insertion and removal can be efficient when the relevant node is known
Weakness: Searching generally takes O(n)
Weakness: No direct random access
Weakness: Requires pointer storage for each node
Binary Search Tree
Strength: Dynamic growth
Strength: Search and insertion can approach O(logn) when balanced
Weakness: Can degrade to O(n) if unbalanced
Weakness: Requires one or more pointers per node
Weakness: More complex than arrays or linked lists
Hash Table
Strength: Average or ideal lookup and insertion near O(1)
Strength: Supports dynamic key–value associations
Weakness: Collisions can reduce performance
Weakness: Requires a good hash function
Weakness: Uses additional memory for buckets and collision handling
Core design principle: Improving time efficiency often requires additional space, while reducing space usage may require more computation.
Overall Relationships Between Algorithms and Data Structures
The examples illustrate several general principles.
Sorted Data Enables Faster Search
Unsorted data generally requires linear search: O(n).
Sorted, directly accessible data enables binary search: O(logn).
Sorting therefore creates an upfront cost that can accelerate later operations.
Contiguous Data Enables Random Access
Arrays store values at predictable, equally spaced addresses.
Arithmetic allows direct access to any index.
This makes arrays suitable for binary search and many sorting algorithms.
Pointers Enable Dynamic Structures
Pointers connect nodes located anywhere in memory.
Linked lists, trees, and hash-table collision chains use pointers.
These structures can grow without requiring all values to be adjacent.
Additional Dimensions Can Improve Search
A linked list organizes values in one chain.
A binary search tree organizes values hierarchically.
The hierarchy allows entire regions of data to be ignored during search.
Divide and Conquer Reduces Work
Binary search repeatedly discards half of the search space.
Merge sort repeatedly divides the data into smaller portions and efficiently recombines them.
The two algorithms both use division, but they have different costs:
Binary search does not need to process every element after discarding half, so it can run in O(logn).
Merge sort must eventually incorporate every element, so it runs in O(nlogn).
Correctness and Efficiency Are Separate
An algorithm can produce the correct answer while still being inefficient.
For example:
Linear search correctly finds a target but may inspect every item.
Bubble sort correctly orders a list but may perform quadratic work.
Merge sort also correctly orders a list while using a more efficient O(nlogn) strategy.
The data structure affects whether an efficient algorithm can be implemented. Binary search is not useful without sorted data and efficient access to the middle element. Dynamic growth is difficult with a fixed contiguous array but natural with linked nodes.
The combination of an appropriate algorithm and an appropriate data structure determines not only whether a program produces correct results, but also how much time and memory it requires.

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