1. Home
  2. Explore
  3. Computer Science
  4. Data Structures and Algorithms

Study methods

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

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 000 and 111. These bits are grouped into larger units, commonly:

  • Bit: A single 000 or 111

  • Byte: Typically 888 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 505050 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:

  1. The first value

  2. The second value

  3. The third value

  4. Every subsequent value until 505050 is found

If the desired value is last, all nnn 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:

  1. Start with the first element.

  2. Compare it with the target.

  3. If it matches, stop.

  4. Otherwise, move to the next element.

  5. Repeat until the target is found or no elements remain.

Efficiency of Linear Search

If there are nnn elements:

  • Worst case: The target is last or absent, requiring approximately nnn checks.

  • Best case: The target is first, requiring only one check.

  • Worst-case upper bound: O(n)O(n)O(n)

  • Best-case lower bound: Ω(1)\Omega(1)Ω(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:

  1. Examine the middle element.

  2. If the middle element equals the target, stop.

  3. If the target is smaller, discard the right half.

  4. If the target is larger, discard the left half.

  5. Repeat the same process on the remaining half.

For example, if the sorted values are:

4, 8, 15, 16, 23, 42, 504,\ 8,\ 15,\ 16,\ 23,\ 42,\ 504, 8, 15, 16, 23, 42, 50

To search for 505050:

  1. Check the middle value, 161616.

  2. Since 50>1650 > 1650>16, ignore all values to the left.

  3. Check the middle of the remaining values, 424242.

  4. Since 50>4250 > 4250>42, check the remaining value, 505050.

  5. Find the target after three checks.

Efficiency of Binary Search

Each comparison cuts the remaining problem approximately in half:

n, n2, n4, n8,…n,\ \frac{n}{2},\ \frac{n}{4},\ \frac{n}{8},\ldotsn, 2n​, 4n​, 8n​,…

The number of divisions required is approximately:

log⁡2n\log_2 nlog2​n

Therefore:

  • Worst-case running time: O(log⁡n)O(\log n)O(logn)

  • Best case: Ω(1)\Omega(1)Ω(1), if the target is initially in the middle

  • Typical exact bound under appropriate conditions: Θ(log⁡n)\Theta(\log n)Θ(logn)

Binary search is much faster than linear search for large collections. However, it depends on two major requirements:

  1. The data must be sorted.

  2. 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:

[4, 8, 15, 16, 23, 42][4,\ 8,\ 15,\ 16,\ 23,\ 42][4, 8, 15, 16, 23, 42]

The elements have indexes:

  • 444 at index 000

  • 888 at index 111

  • 151515 at index 222

  • 161616 at index 333

  • 232323 at index 444

  • 424242 at index 555

Most programming languages use zero-based indexing, meaning that the first element is at index 000 rather than index 111.

Calculating an Array Position

If an array has seven elements, its indexes are:

0, 1, 2, 3, 4, 5, 60,\ 1,\ 2,\ 3,\ 4,\ 5,\ 60, 1, 2, 3, 4, 5, 6

The middle index can be calculated by dividing the number of elements by 222 and rounding down:

⌊72⌋=3\left\lfloor \frac{7}{2} \right\rfloor = 3⌊27​⌋=3

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:

address=base address+(index×element size)\text{address} = \text{base address} + (\text{index} \times \text{element size})address=base address+(index×element size)

Because the computer can calculate this address directly, accessing an array element by index takes constant time:

O(1)O(1)O(1)

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:

0, 1, 2, 3,…0,\ 1,\ 2,\ 3,\ldots0, 1, 2, 3,…

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))O(f(n))O(f(n)), describes an upper bound on an algorithm’s growth rate.

For example:

O(n)O(n)O(n)

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)O(1)O(1) — constant time

  • O(log⁡n)O(\log n)O(logn) — logarithmic time

  • O(n)O(n)O(n) — linear time

  • O(nlog⁡n)O(n \log n)O(nlogn) — linearithmic time

  • O(n2)O(n^2)O(n2) — quadratic time

Big Omega: Lower Bound

Big Omega, written Ω(f(n))\Omega(f(n))Ω(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:

Ω(1)\Omega(1)Ω(1)

Big Theta: Tight Bound

Big Theta, written Θ(f(n))\Theta(f(n))Θ(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:

Θ(f(n))\Theta(f(n))Θ(f(n))

These notations focus on growth as nnn becomes large. Constants and lower-order terms are usually ignored because they have less effect on large inputs.

For example:

n2−n2=n22−n2\frac{n^2-n}{2} = \frac{n^2}{2}-\frac{n}{2}2n2−n​=2n2​−2n​

is dominated by the n2n^2n2 term as nnn grows. It is therefore described as:

O(n2)O(n^2)O(n2)

This does not mean the algorithm takes exactly n2n^2n2 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:

  1. Compare the first and second elements.

  2. If they are out of order, swap them.

  3. Compare the second and third elements.

  4. Continue comparing adjacent pairs.

  5. 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 them

The loop stops at n−2n-2n−2 because each comparison involves both element iii and element i+1i+1i+1. The final valid comparison is therefore between indexes n−2n-2n−2 and n−1n-1n−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 nnn elements:

  • A pass compares approximately n−1n-1n−1 adjacent pairs.

  • In the worst case, approximately nnn passes may be needed.

This produces approximately:

n(n−1)n(n-1)n(n−1)

comparisons, which is on the order of:

O(n2)O(n^2)O(n2)

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

  1. Search the entire list for the smallest element.

  2. Swap it with the first element.

  3. Search the remaining unsorted portion for the next-smallest element.

  4. Swap it into the second position.

  5. Continue until all elements are placed.

For example:

  • First, select the smallest value and place it at index 000.

  • Next, select the smallest value from indexes 111 through n−1n-1n−1 and place it at index 111.

  • Continue with indexes 222, 333, 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 i

After each iteration, the sorted region grows by one element, while the unsorted region shrinks.

Selection Sort Efficiency

The first search examines approximately n−1n-1n−1 other elements. The next examines approximately n−2n-2n−2, then n−3n-3n−3, and so on.

The total number of comparisons is approximately:

(n−1)+(n−2)+(n−3)+⋯+1(n-1)+(n-2)+(n-3)+\cdots+1(n−1)+(n−2)+(n−3)+⋯+1

This sum equals:

n(n−1)2\frac{n(n-1)}{2}2n(n−1)​

Expanding it:

n2−n2=n22−n2\frac{n^2-n}{2} = \frac{n^2}{2}-\frac{n}{2}2n2−n​=2n2​−2n​

The n2n^2n2 term dominates for large values of nnn, so selection sort has running time:

O(n2)O(n^2)O(n2)

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)O(n^2)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)O(n^2)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

  1. Divide the list into two halves.

  2. Recursively divide each half into smaller halves.

  3. Continue until each sublist contains one element.

  4. Treat each one-element list as already sorted.

  5. Merge pairs of sorted sublists.

  6. 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:

[4, 16][4,\ 16][4, 16]

and

[8, 15][8,\ 15][8, 15]

The merge process compares the first unused element of each list:

  1. Compare 444 and 888; take 444.

  2. Compare 161616 and 888; take 888.

  3. Compare 161616 and 151515; take 151515.

  4. Take the remaining 161616.

The result is:

[4, 8, 15, 16][4,\ 8,\ 15,\ 16][4, 8, 15, 16]

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 nnn elements.

  • The next level has two sections of approximately n2\frac{n}{2}2n​ elements.

  • Further levels divide the data into smaller sections.

  • The number of division levels is approximately log⁡2n\log_2 nlog2​n.

  • Each level processes all nnn elements during merging.

Therefore, merge sort has running time:

O(nlog⁡n)O(n\log n)O(nlogn)

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)O(n^2)O(n2) time and little extra space

  • Selection sort: approximately O(n2)O(n^2)O(n2) time and little extra space

  • Merge sort: approximately O(nlog⁡n)O(n\log n)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:

  1. Reject the new value because there is no adjacent space.

  2. 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:

4, 8, 15, 16, 23, 424,\ 8,\ 15,\ 16,\ 23,\ 424, 8, 15, 16, 23, 42

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 888, 161616, or 100100100 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:

  1. The actual data value

  2. The address of the next node

The address or reference to another node is often called a pointer.

For example, a node containing 424242 might also store the address of the node containing 505050.

Conceptually:

4→8→15→16→23→42→504 \rightarrow 8 \rightarrow 15 \rightarrow 16 \rightarrow 23 \rightarrow 42 \rightarrow 504→8→15→16→23→42→50

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:

  1. Identify the node before the target.

  2. Change its pointer so that it skips the target.

  3. The target node is no longer part of the list.

To insert a node:

  1. Allocate a new node.

  2. Set its pointer to the appropriate next node.

  3. 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)O(n)O(n).

  • Accessing the kkkth element generally takes O(k)O(k)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 50

To search for 151515:

  1. Start at 161616.

  2. Since 15<1615 < 1615<16, move left to 888.

  3. Since 15>815 > 815>8, move right to 151515.

  4. 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:

O(log⁡n)O(\log n)O(logn)

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
     \
      16

This structure behaves like a linked list, causing search time to degrade to:

O(n)O(n)O(n)

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 000

  • B to index 111

  • C to index 222

  • D to index 333

Because computers represent characters using encodings such as ASCII or Unicode, a character can be converted to a number. For uppercase ASCII letters:

  • AAA has a numerical code of 656565

  • BBB has a numerical code of 666666

  • DDD has a numerical code of 686868

Subtracting 656565 gives:

index=character code−65\text{index} = \text{character code} - 65index=character code−65

Thus:

A↦0,B↦1,D↦3A \mapsto 0,\quad B \mapsto 1,\quad D \mapsto 3A↦0,B↦1,D↦3

This involves a constant number of operations, independent of the total number of stored names.

Hash Table Lookup

To find a name:

  1. Examine the relevant key, such as the first letter.

  2. Apply the hash function.

  3. Obtain an array index.

  4. Jump directly to that index.

  5. Search the associated location or bucket.

With a good hash function and few conflicts, lookup and insertion can approach:

O(1)O(1)O(1)

Collisions

A collision occurs when multiple keys produce the same hash value.

For example, both David and Doug begin with DDD, 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 name

The 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:

O(n)O(n)O(n)

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,yx,yx,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 323232 or 646464 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:

(x,y)(x,y)(x,y)

or:

(latitude,longitude)(\text{latitude},\text{longitude})(latitude,longitude)

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)O(1)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)O(n)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(log⁡n)O(\log n)O(logn) when balanced

  • Weakness: Can degrade to O(n)O(n)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)O(1)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)O(n)O(n).

  • Sorted, directly accessible data enables binary search: O(log⁡n)O(\log n)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(log⁡n)O(\log n)O(logn).

  • Merge sort must eventually incorporate every element, so it runs in O(nlog⁡n)O(n\log n)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(nlog⁡n)O(n\log n)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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent