Introduction to Data Structures
📊 Data Structures: Sequences, Sets, Linked Lists, and Dynamic Arrays
This lecture introduces fundamental data structures, differentiating between interfaces and implementations, and exploring static arrays, linked lists, and dynamic arrays for managing sequences of data.
💡 Interface vs. Data Structure (API vs. ADT)
A crucial distinction in algorithms and data structures is between interfaces and data structures (also known as APIs or ADTs).
Interface (API/ADT):
Defines what you want to do.
Acts as a specification for storing data.
Specifies what data can be stored and what operations are supported, along with their meaning.
Data Structure:
Defines how you do it.
Provides the actual representation of the data.
Gives algorithms for supporting the specified operations.
This separation is vital because:
The same problem can be solved by multiple data structures.
Different data structures offer different advantages (e.g., speed for certain operations).
Choosing the right data structure depends on the specific use case.
🏷️ Core Interfaces: Set and Sequence
We will focus on two primary interfaces for storing n items:
Set:
Focuses on the values of the items.
Often implies maintaining items in sorted order.
Supports operations like searching for a given value (key).
Example: A mathematical set where order doesn't matter, only membership.
Sequence:
Focuses on maintaining a specific order of items.
Items are indexed (e.g., first item, second item).
Example:
[5, 2, 9, 7]where5is the first item,2is the second, etc. (like a Python list).
This lecture will primarily focus on the Sequence interface.
🛠️ Data Structure Tools: Arrays vs. Pointers
Two main approaches to building data structures are:
Arrays:
Store data in contiguous blocks of memory.
Enable direct, indexed access.
Example: Static arrays, dynamic arrays.
Pointers (Linked Data Structures):
Store data in nodes that are linked together.
Nodes can be arbitrarily located in memory.
Order is maintained by explicit pointers.
Example: Linked lists.
🧊 Static Sequence Interface
The static sequence interface deals with sequences where the number of items (n) does not change after creation. The items themselves can be modified.
nitems: Labeledx_0tox_{n-1}(Python-style indexing).Operations:
build(x): Creates a new static sequence of sizenwith items in a specified order. Takes an iterablex.length(): Returns the fixed number of itemsn.iter_sequence(): Outputs itemsx_0throughx_{n-1}in order. Takes at least linear time.get_at(i): Returns the itemx_iat indexi.set_at(i, new_item): Changes the itemx_iat indexitonew_item.
💾 Static Arrays: A Data Structure for Static Sequences
The natural implementation for the static sequence interface is a static array.
Memory Model (Word RAM):
Memory is an array of
w-bit words.Random Access Memory (RAM): Any word can be accessed in constant time.
An array is a consecutive chunk of memory.
Accessing
array[i]means accessingmemory[address_of_array + i]. This is offset arithmetic.This allows
get_atandset_atto be constant time operations.Word Size (
w): Must be at least logn to addressnitems. This accounts for scalability in theoretical models, wherencan be very large.
Performance of Static Arrays:
Operation
Time Complexity
Explanation
build(x)Θ(n)
Requires allocating a new array of size
nand copyingnitems. Memory allocation is assumed to take linear time.length()Θ(1)
The length
nis stored and returned directly.iter_sequence()Θ(n)
Iterating through all
nitems requires accessing each one.get_at(i)Θ(1)
Due to random access memory and contiguous storage, any element can be accessed directly using its index.
set_at(i)Θ(1)
Similar to
get_at, an element can be modified directly at its index.Memory Allocation Model:
Allocating an array of size
ntakes Θ(n) time.This models the work of finding a contiguous block of memory and initializing it (e.g., to zeros).
Space used is proportional to time used, which is a reasonable assumption.
🔄 Dynamic Sequence Interface
The dynamic sequence interface extends the static sequence by allowing the number of items to change. It includes all static operations plus dynamic ones.
New Dynamic Operations:
insert_at(i, x): Insertsxat positioni. All itemsx_i, x_{i+1}, ...shift tox_{i+1}, x_{i+2}, ....delete_at(i): Deletes the item at positioni. All itemsx_{i+1}, x_{i+2}, ...shift tox_i, x_{i+1}, ....
Special Cases (for efficiency):
insert_first(x): Insert at index 0.delete_first(): Delete at index 0.insert_last(x): Insert at indexn.delete_last(): Delete at indexn-1.These special cases are often more efficient to implement than general
insert_at/delete_at.
🔗 Linked Lists: A Data Structure for Dynamic Sequences
Linked lists are a pointer-based data structure designed to handle dynamic operations efficiently, particularly at the ends.
Structure:
Items are stored in nodes.
Each node contains:
An
item(the actual data value).A
nextfield (a pointer) to the subsequent node in the sequence.
The entire list is accessed via a
headpointer to the first node.Pointers are stored in a single
w-bit word and can be dereferenced in constant time.Nodes can be scattered anywhere in memory; their logical order is defined by the
nextpointers.
Performance of Linked Lists: | Operation | Time Complexity | Explanation
Dynamic Arrays
Dynamic Arrays
Linked Lists
buildΘ(n)
Θ(n)
lengthΘ(1)
Θ(1)
iterΘ(n)
Θ(n)
get_atΘ(1)
Θ(n)
set_atΘ(1)
Θ(n)
insert_firstΘ(n)
Θ(1)
delete_firstΘ(n)
Θ(1)
insert_lastΘ(1) amortized
Θ(1) (with tail pointer)
delete_lastΘ(1) amortized
Θ(n) (or Θ(1) with doubly linked list)
insert_atΘ(n)
Θ(n)
delete_atΘ(n)
Θ(n)
📈 Dynamic Arrays: Best of Both Worlds
Dynamic arrays (often called "lists" in Python) combine the strengths of static arrays and linked lists to provide efficient general-purpose sequence operations.
Core Idea:
Relax the constraint that the array's size must exactly equal
n(number of items).Maintain an underlying static array (
A) whosesizeis roughly proportional ton.Specifically,
sizeis Θ(n) andsize≥n. A common strategy issize≤2n.The array
Astores the sequence itemsx_0tox_{n-1}in its firstnslots. The remainingsize - nslots are unused "slack space."
Key Invariant:
A[i]always representsx_i. This allowsget_atandset_atto remain Θ(1).insert_last(x)Algorithm:Check for Space: If
n < size, there is slack space.Set
A[n] = x.Increment
n(the logical length).This is a Θ(1) operation.
Resize (if
n == size): If the array is full:Allocate a new array (
A_new) with a largersize. A common strategy is to double the size (e.g.,size_new = 2 * size).Copy all
nexisting items fromAtoA_new.Deallocate the old array
A.Set
A = A_new.Then, proceed with step 1 (set
A[n] = x, incrementn).This resize operation takes Θ(n) time due to allocation and copying.
Amortized Analysis of
insert_last:While individual
insert_lastoperations can be expensive (Θ(n) when resizing), most are cheap (Θ(1)).Consider a sequence of
ninsert_lastoperations starting from an empty array.Resizes occur when
nreaches powers of 2 (e.g., 1, 2, 4, 8, ...).The total cost of all resizes is: 1 + 2 + 4 + ... + \text{current_size} \approx \sum_{i=0}^{\log n} 2^i.
This is a geometric series, whose sum is dominated by its largest term. The sum is Θ(2logn)=Θ(n).
Since
noperations cost Θ(n) total time, the average cost per operation is nΘ(n)=Θ(1).This is called amortized constant time: "an operation takes T(n) amortized time if any k of those operations take at most k⋅T(n) time."
delete_last():Simply decrement
n. The item is logically removed.No need to resize immediately. The slack space remains.
To prevent excessive unused space, a more advanced strategy might shrink the array if
nbecomes too small (e.g.,n < size / 4). This also results in amortized constant time.
📊 Summary of Data Structure Performance
Operation | Static Array | Linked List | Dynamic Array |
|---|---|---|---|
| Θ(n) | Θ(n) | Θ(n) |
| Θ(1) | Θ(1) | Θ(1) |
| Θ(n) | Θ(n) | Θ(n) |
| Θ(1) | Θ(n) | Θ(1) |
| Θ(1) | Θ(n) | Θ(1) |
| Θ(n) | Θ(1) | Θ(n) |
| Θ(n) | Θ(1) | Θ(n) |
| Θ(n) | Θ(1) | Θ(1) amortized |
| Θ(n) | Θ(n) (or Θ(1) with tail/doubly) | Θ(1) amortized |
| Θ(n) | Θ(n) | Θ(n) |
| Θ(n) | Θ(n) | Θ(n) |
Dynamic arrays (Python lists) offer:
Fast random access (
get_at,set_at) like static arrays.Fast appends/removals at the end (
insert_last,delete_last) in amortized constant time, making them efficient for many common use cases.Operations involving changes in the middle or at the beginning (
insert_at,delete_at,insert_first,delete_first) still require shifting elements, leading to Θ(n) worst-case time.

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