1. Home
  2. Explore
  3. Computer Science
  4. Introduction to Data Structures

Study methods

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

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:

  1. 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.

  2. Sequence:

    • Focuses on maintaining a specific order of items.

    • Items are indexed (e.g., first item, second item).

    • Example: [5, 2, 9, 7] where 5 is the first item, 2 is 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:

  1. Arrays:

    • Store data in contiguous blocks of memory.

    • Enable direct, indexed access.

    • Example: Static arrays, dynamic arrays.

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

  • n items: Labeled x_0 to x_{n-1} (Python-style indexing).

  • Operations:

    • build(x): Creates a new static sequence of size n with items in a specified order. Takes an iterable x.

    • length(): Returns the fixed number of items n.

    • iter_sequence(): Outputs items x_0 through x_{n-1} in order. Takes at least linear time.

    • get_at(i): Returns the item x_i at index i.

    • set_at(i, new_item): Changes the item x_i at index i to new_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 accessing memory[address_of_array + i]. This is offset arithmetic.

    • This allows get_at and set_at to be constant time operations.

    • Word Size (w): Must be at least log⁡n\log nlogn to address n items. This accounts for scalability in theoretical models, where n can be very large.

  • Performance of Static Arrays:

    Operation

    Time Complexity

    Explanation

    build(x)

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

    Requires allocating a new array of size n and copying n items. Memory allocation is assumed to take linear time.

    length()

    Θ(1)\Theta(1)Θ(1)

    The length n is stored and returned directly.

    iter_sequence()

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

    Iterating through all n items requires accessing each one.

    get_at(i)

    Θ(1)\Theta(1)Θ(1)

    Due to random access memory and contiguous storage, any element can be accessed directly using its index.

    set_at(i)

    Θ(1)\Theta(1)Θ(1)

    Similar to get_at, an element can be modified directly at its index.

  • Memory Allocation Model:

    • Allocating an array of size n takes Θ(n)\Theta(n)Θ(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): Inserts x at position i. All items x_i, x_{i+1}, ... shift to x_{i+1}, x_{i+2}, ....

    • delete_at(i): Deletes the item at position i. All items x_{i+1}, x_{i+2}, ... shift to x_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 index n.

    • delete_last(): Delete at index n-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 next field (a pointer) to the subsequent node in the sequence.

    • The entire list is accessed via a head pointer 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 next pointers.

  • Performance of Linked Lists: | Operation | Time Complexity | Explanation

    Dynamic Arrays

    Dynamic Arrays

    Linked Lists

    build

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

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

    length

    Θ(1)\Theta(1)Θ(1)

    Θ(1)\Theta(1)Θ(1)

    iter

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

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

    get_at

    Θ(1)\Theta(1)Θ(1)

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

    set_at

    Θ(1)\Theta(1)Θ(1)

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

    insert_first

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

    Θ(1)\Theta(1)Θ(1)

    delete_first

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

    Θ(1)\Theta(1)Θ(1)

    insert_last

    Θ(1)\Theta(1)Θ(1) amortized

    Θ(1)\Theta(1)Θ(1) (with tail pointer)

    delete_last

    Θ(1)\Theta(1)Θ(1) amortized

    Θ(n)\Theta(n)Θ(n) (or Θ(1)\Theta(1)Θ(1) with doubly linked list)

    insert_at

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

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

    delete_at

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

    Θ(n)\Theta(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) whose size is roughly proportional to n.

    • Specifically, size is Θ(n)\Theta(n)Θ(n) and size ≥n\ge n≥n. A common strategy is size ≤2n\le 2n≤2n.

    • The array A stores the sequence items x_0 to x_{n-1} in its first n slots. The remaining size - n slots are unused "slack space."

  • Key Invariant: A[i] always represents x_i. This allows get_at and set_at to remain Θ(1)\Theta(1)Θ(1).

  • insert_last(x) Algorithm:

    1. Check for Space: If n < size, there is slack space.

      • Set A[n] = x.

      • Increment n (the logical length).

      • This is a Θ(1)\Theta(1)Θ(1) operation.

    2. Resize (if n == size): If the array is full:

      • Allocate a new array (A_new) with a larger size. A common strategy is to double the size (e.g., size_new = 2 * size).

      • Copy all n existing items from A to A_new.

      • Deallocate the old array A.

      • Set A = A_new.

      • Then, proceed with step 1 (set A[n] = x, increment n).

      • This resize operation takes Θ(n)\Theta(n)Θ(n) time due to allocation and copying.

  • Amortized Analysis of insert_last:

    • While individual insert_last operations can be expensive (Θ(n)\Theta(n)Θ(n) when resizing), most are cheap (Θ(1)\Theta(1)Θ(1)).

    • Consider a sequence of n insert_last operations starting from an empty array.

    • Resizes occur when n reaches 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 Θ(2log⁡n)=Θ(n)\Theta(2^{\log n}) = \Theta(n)Θ(2logn)=Θ(n).

    • Since n operations cost Θ(n)\Theta(n)Θ(n) total time, the average cost per operation is Θ(n)n=Θ(1)\frac{\Theta(n)}{n} = \Theta(1)nΘ(n)​=Θ(1).

    • This is called amortized constant time: "an operation takes T(n)T(n)T(n) amortized time if any kkk of those operations take at most k⋅T(n)k \cdot T(n)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 n becomes 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

build

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

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

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

length

Θ(1)\Theta(1)Θ(1)

Θ(1)\Theta(1)Θ(1)

Θ(1)\Theta(1)Θ(1)

iter

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

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

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

get_at

Θ(1)\Theta(1)Θ(1)

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

Θ(1)\Theta(1)Θ(1)

set_at

Θ(1)\Theta(1)Θ(1)

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

Θ(1)\Theta(1)Θ(1)

insert_first

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

Θ(1)\Theta(1)Θ(1)

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

delete_first

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

Θ(1)\Theta(1)Θ(1)

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

insert_last

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

Θ(1)\Theta(1)Θ(1)

Θ(1)\Theta(1)Θ(1) amortized

delete_last

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

Θ(n)\Theta(n)Θ(n) (or Θ(1)\Theta(1)Θ(1) with tail/doubly)

Θ(1)\Theta(1)Θ(1) amortized

insert_at

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

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

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

delete_at

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

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

Θ(n)\Theta(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)\Theta(n)Θ(n) worst-case time.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent