Linear Data Structures: Arrays, Lists, Stacks and Queues

Learn how the basic linear data structures store a sequence and what each operation costs. Separate an abstract data type from its implementation, see why array indexing is fast, build a dynamic array and explain with amortized analysis why appending stays cheap even though resizing copies everything. Implement singly, doubly and circular linked lists, then use stacks, queues and deques for bracket matching, expression evaluation, scheduling and buffers. Finish by choosing the right structure for a program's access pattern and justifying it with costs. Examples are in Python.

IntermediateLesson 3 of 10 in Data Structures and Algorithms Course

What you will learn

  1. Separate what a structure promises (its operations and how they behave) from how it stores data, and use a simple model of memory to predict what each way of storing data costs.
    • Specify an abstract data type and keep it apart from its implementation
      Define an abstract data type by its operations, their effects and their error cases, and see how one abstract data type can have several implementations with different costs.
    • Predict costs from how memory stores data
      Use a simple model of memory to see why array indexing is fast, why an array cannot simply grow in place, and what references and locality mean for linked structures.
  2. Work with fixed-size arrays, implement a dynamic array that resizes itself, and explain why appending stays fast over any long run even though an occasional append copies every element.
    • Use static arrays and count the cost of shifting
      Read, update, insert and delete in a fixed-capacity array, and count how many elements each operation has to move.
    • Implement a dynamic array
      Keep size and capacity apart, and write the append, insert and delete methods of an array that replaces its storage when it fills up.
    • Explain the cost of resizing with amortized analysis
      Count the copying work in a long run of appends, explain why doubling gives a constant amortized cost and growing by a fixed amount does not, and avoid resizing back and forth.
  3. Implement singly, doubly and circular linked lists, change their links in a safe order, and know which of their operations are fast and which are not.
    • Implement a singly linked list
      Build a list of nodes joined by next references, and insert, remove and traverse at the head, at the tail and after a given node.
    • Implement doubly and circular linked lists
      Add backward links and sentinel nodes so that inserting and removing anywhere takes constant time, and link the last node back to the first for round-robin work.
  4. Implement the three restricted-access abstract data types with arrays and linked lists, and apply them to classic problems such as matching brackets, evaluating expressions and serving requests in order.
    • Use and implement a stack
      Apply last-in, first-out access, implement a stack with a Python list or a linked list, and use it to match brackets, evaluate postfix expressions and track history.
    • Use and implement a queue
      Apply first-in, first-out access, implement a queue with a circular array or a linked list, and avoid the slow list-based queue.
    • Use and implement a deque
      Add and remove at both ends of a double-ended queue, implement it with a circular array or a doubly linked list, and use Python's deque for buffers, rotation and sliding windows.
  5. Compare the costs of every structure in this material side by side, and choose the one that fits how a program reads and changes its data, with a justification based on those costs.
    • Compare operation costs across structures
      Set the costs of arrays, linked lists, stacks, queues and deques side by side, and weigh worst-case against amortized bounds, memory use and real-world speed.
    • Match an access pattern to a structure
      Follow a short method to choose a structure from the operations a program performs, and justify the choice with the costs of those operations.

Linear Data Structures study guide

5 chapters

1

Describe data structures through abstract data types and memory

An interface describes what operations mean; a memory layout explains what they cost. Connect those two views by specifying a collection, tracing the references that store it, and identifying the conditions its methods must preserve. The same ordered data can live in contiguous slots or a chain of nodes, and that choice changes how the program reaches and changes an element. Python examples make both the interface and the stored state visible.

1.1 Interfaces, implementations, and invariants

A collection can promise a behavior without committing to a memory layout. That promise lets you reason about a program before choosing how to store its data.

Specify the behavior

An abstract data type (ADT) describes operations and their meaning. For each operation, specify its inputs, return value, effect on the collection, and error cases. For a stack, push(e) adds an element at the top; pop() removes and returns the top; top() reads it without removal. is_empty() and len() report the state. An empty pop() or top() raises an exception.

This contract makes client code predictable. If None is a valid stored value, returning None for an empty pop would make success and failure indistinguishable. An exception reports failure separately.

The sequence ADT arranges items by position. It supports indexed reads and updates, insertion, deletion, and ordered traversal. A set interface instead finds, inserts, and deletes by key. Position 4 means a place in a sequence; key 4 means the identity used to find an item.

Choose the representation

A data structure supplies the storage and algorithms behind an ADT. Both dynamic arrays and linked lists can implement a sequence, with different costs:

Sequence operationDynamic arrayLinked list
Read an arbitrary indexO(1)O(n)
Insert at the frontO(n)O(1)

The interface alone does not tell you these costs. A class is a programming tool for implementing a contract, not the ADT itself. The same ADT can be implemented in different languages and with different structures.

Hide internal details

Here is a complete small stack wrapper. The list's end is the top.

class Empty(Exception):
    pass

class ArrayStack:
    def __init__(self):
        self._data = []

    def __len__(self):
        return len(self._data)

    def is_empty(self):
        return len(self) == 0

    def push(self, e):
        self._data.append(e)

    def top(self):
        if self.is_empty():
            raise Empty("stack is empty")
        return self._data[-1]

    def pop(self):
        if self.is_empty():
            raise Empty("stack is empty")
        return self._data.pop()

After pushing "draft" and then "save", top() returns "save" and leaves the size at 2. pop() returns "save" and leaves the size at 1. The wrapper exposes no operation for changing a middle element. Client code that uses this interface can also use a linked implementation with the same behavior.

In Python, an initial underscore marks an internal attribute by convention; it does not prevent access. Reaching into _data breaks the separation that makes replacement possible.

State what must stay true

A representation invariant describes a valid internal state. Examples include "The size counter equals the number of stored elements" and "The tail refers to the final node, or is None when empty." A method can temporarily change links while it runs, but must restore the invariant before returning. Check both the returned result and the stored state when debugging: a method can return the right element while leaving a stale tail behind.

Key Takeaways

  • An ADT specifies behavior, including errors; a data structure implements it.
  • One ADT can have several implementations with different operation costs.
  • Client code stays independent when it uses only the public interface.
  • Every method must restore the representation invariant before returning.

1.2 Addresses, references, and locality

Array access and linked-list access do different work because they find elements differently. A simple memory model makes those costs visible.

Locate an array element

Treat memory as a row of numbered bytes. An address identifies a byte; reading or writing a fixed-size word at a known address takes constant time in this model. Computing an address and following a reference also take O(1) time. Memory examples here use 8-byte words.

An array reserves one contiguous block with equal-size slots. Its index gives an offset from the start:

address(i)=start+i×slot size

For 8-byte numbers starting at address 2000, index 7 is at 2000+7×8=2056. The calculation has the same number of steps for index 7 as for index 7000, so access is O(1). Index 0 needs no offset. With length n, the last valid nonnegative index is n - 1; index n is out of bounds. Python reports an invalid list index with IndexError.

A row-major two-dimensional array lays out complete rows in sequence. With C columns, skip r * C slots to reach row r, then c more to reach its column:

address(r,c)=start+(rC+c)×slot size

In a 4 by 5 table of 8-byte values starting at 1000, position (2, 3) is 13 slots from the start, at 1000+13×8=1104. This formula describes a flat rectangular layout; a Python list of row lists instead stores references to separate row objects.

Store values or references

A compact array stores values directly, all of one type. For example, array('i', [3, 1, 4]) from Python's array module stores C integers; bytes stores byte values. A referential array, such as a CPython list, stores equal-size references to objects. The objects can have different types and sizes because the slots hold their references, not the objects themselves.

Copying a reference does not copy its object:

grid = [[0] * 3] * 3
grid[0][0] = 1
# [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Multiplication repeats references to one inner list. All three rows therefore show the mutation. To build independent rows, create each row separately:

grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
# [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Follow links and use nearby memory

A linked-list node stores an element and a reference to the next node. Nodes can occupy unrelated addresses. Starting at the head, reaching index i requires following i links: O(i) time. Each link is cheap, but the number of links grows with the position.

Arrays also benefit from locality. A processor loads nearby memory into its cache in chunks, so scanning consecutive slots often reuses data already loaded. Scattered nodes can cause more waiting for memory. Both full traversals cost O(n), yet the array often runs faster. Linked nodes also need link fields and separate-object overhead.

An array's neighboring memory may belong to other data, so growth generally requires a new block and a copy. Spare slots postpone that copy; they do not change the address formula within the current block.

Key Takeaways

  • Contiguous equal-size slots make address calculation and indexing constant time.
  • Row-major indexing uses the column count to skip complete rows.
  • A Python list stores references; repeated references can share one mutable object.
  • Linked indexing follows a chain, while array traversal often benefits from locality.
  • Growing an array may require allocating a new block and copying its elements.
2

Build and analyze arrays that grow

An array makes indexed access cheap, but inserting into its sequence can move many elements. Growth adds another kind of work: replacing full storage and copying its contents. Build those operations with explicit size and capacity, then count a complete run of appends to explain their amortized cost. Safe shift directions and separate resize thresholds connect the implementation details to its correctness and performance.

2.1 Packed arrays and safe shifting

A fixed-capacity array can hold a sequence shorter than its storage. To preserve position-based access, keep the sequence packed at the front and track how many slots are in use.

Separate storage from the sequence

For data = [None] * 8, capacity is 8. If the sequence contains "A", "C", and "D", its size is 3 and the used indices are 0, 1, and 2. Reading or updating a valid position costs O(1). A full static array cannot accept another element without replacement storage.

A read or deletion requires 0 <= k < n. Insertion allows 0 <= k <= n: inserting at n means adding just after the last element. The unused slots are storage, not extra elements in the sequence.

Insert by shifting right

To insert "B" at index 1 in the three-element sequence, move "D" from 2 to 3, then "C" from 1 to 2. Finally write "B" at 1 and increase the size to 4. The result is ['A', 'B', 'C', 'D'] followed by unused slots.

The loop must start at the back. Starting with data[2] = data[1] would overwrite "D" before it was saved. In general, shift the used positions from n - 1 down through k:

# Requires a valid insertion index and a spare slot.
for j in range(n, k, -1):
    data[j] = data[j - 1]
data[k] = value
n += 1

Exactly n−k old elements move, where n is the size before insertion. Inserting at index 3 of a 10-element sequence moves indices 3 through 9: 7 moves. Include the new write and size update when stating the time: O(n−k+1). At the back this is O(1); at the front it is O(n).

Delete by shifting left

Deleting index 1 from ['A', 'B', 'C', 'D'] saves "B", copies "C" into 1, and copies "D" into 2. The last formerly used slot must then be cleared:

# Requires 0 <= k < n.
removed = data[k]
for j in range(k, n - 1):
    data[j] = data[j + 1]
data[n - 1] = None
n -= 1

Clearing the slot releases the array's reference to the former last element. It also keeps the unused region easy to inspect. Clearing is not what removes the element from the logical sequence; the size determines which slots belong to it.

Deletion moves n−k−1 elements and costs O(n−k) including constant bookkeeping. Deleting index 3 from size 10 moves 6 elements. Deleting the final element moves none but still takes constant time.

Distinguish lookup from search

Knowing an index gives immediate access. Knowing a value does not reveal its index. An unsorted array may require inspecting all n entries, so linear search is O(n). A sorted array permits binary search in O(log⁡n) by repeatedly halving the remaining interval, but maintaining sorted order still requires shifts on insertion.

A static array fits a known maximum, such as a fixed-size image or a sensor buffer. Its fixed storage removes resize costs; the access pattern still determines whether shifting is expensive.

Key Takeaways

  • Used elements occupy indices 0 through size minus 1 without gaps.
  • Shift right from the back for insertion; shift left from the gap for deletion.
  • Insertion moves n − k elements, while deletion moves n − k − 1.
  • Constant-time indexing does not make value search constant time.
  • A fixed capacity prevents resizing but does not prevent shifting.

2.2 A dynamic array implementation

A dynamic array replaces its backing storage when it fills up. Its public sequence grows while each individual backing array keeps a fixed capacity.

Keep size and capacity distinct

Size counts stored elements. Capacity counts available slots. With size 5 and capacity 8, positions 0 through 4 hold elements and positions 5 through 7 are unused. Reads and updates check against size, even though the backing array has more slots.

The implementation below starts at capacity 1 and doubles when full. It deliberately accepts only nonnegative indices, so the bounds stay explicit.

class DynamicArray:
    def __init__(self):
        self._n = 0
        self._capacity = 1
        self._A = [None]

    def __len__(self):
        return self._n

    def _resize(self, capacity):
        B = [None] * capacity
        for k in range(self._n):
            B[k] = self._A[k]
        self._A = B
        self._capacity = capacity

    def get(self, i):
        if not 0 <= i < self._n:
            raise IndexError("invalid index")
        return self._A[i]

    def set(self, i, value):
        if not 0 <= i < self._n:
            raise IndexError("invalid index")
        self._A[i] = value

    def append(self, value):
        self.insert(self._n, value)

    def insert(self, k, value):
        if not 0 <= k <= self._n:
            raise IndexError("invalid index")
        if self._n == self._capacity:
            self._resize(2 * self._capacity)
        for j in range(self._n, k, -1):
            self._A[j] = self._A[j - 1]
        self._A[k] = value
        self._n += 1

    def delete(self, k):
        if not 0 <= k < self._n:
            raise IndexError("invalid index")
        value = self._A[k]
        for j in range(k, self._n - 1):
            self._A[j] = self._A[j + 1]
        self._A[self._n - 1] = None
        self._n -= 1
        return value

_resize is internal: callers supply a positive capacity large enough for the stored elements. Copying finishes before _A is replaced, so every read during the loop still uses the old storage. The copied entries are references; the objects are not duplicated.

Trace the growth

Append 10, 20, 30, 40, and 50. The first append fills capacity 1. The second copies 1 element into capacity 2. The third copies 2 into capacity 4. The fourth fits without a copy. The fifth copies 4 into capacity 8. Final size is 5, with 3 spare slots and 7 copied entries across all resizes.

A read at index 5 must fail: that slot exists in storage but is beyond the sequence. Insertion at index 5 is valid because it extends the sequence at its end.

Account for each kind of work

An insert with room costs O(n−k+1) for shifting and the new write. If it resizes, it also copies all n existing entries, making that individual insertion O(n) even at the end.

The implementation keeps its capacity after deletions. To release spare memory, it can halve capacity at one-quarter occupancy while preserving a minimum capacity of 1. Shrinking at half occupancy would put it directly on the growth boundary and cause repeated copying under alternating appends and pops.

CPython's list, Java's ArrayList, and C++'s std::vector provide dynamic arrays. Python hides capacity and reports size with len. Rebuilding storage with one extra slot for every append loses the benefit of spare capacity and makes a long run of appends quadratic.

Key Takeaways

  • Size counts elements; capacity counts reserved slots.
  • Resize before writing into a full backing array, and copy before replacing it.
  • Read and update bounds use size; insertion also allows the position at size.
  • Shifting and resizing are separate sources of insertion cost.
  • A single resizing append is linear even though appends are cheap over a run.
  • Shrinking at one-quarter occupancy leaves space between resize thresholds.

2.3 Why proportional growth keeps appends cheap

A fast typical append and a slow resizing append belong to the same implementation. Amortized analysis gives a guarantee for the whole run without pretending that each operation costs the same.

Count the complete run

Start empty at capacity 1 and double whenever full. During 16 appends, resizes copy 1, 2, 4, and 8 entries: 15 copies. The 16 new entries also need writes, so there are 31 element operations. The next append copies 16 entries before writing its new value.

The 17th operation is expensive, but it does not make the complete run quadratic. For n appends, the copied array sizes form a geometric series:

1+2+4+⋯+2k=2k+1−1<2n

Here 2k is the largest power of 2 below n; for a run with no resize the copy total is zero. Adding n new writes gives fewer than 3n element operations. Allocation and initialization of these geometrically growing arrays also have linear total cost in this model.

Thus appending is amortized O(1). This bounds the worst-case total over every run of a given length and divides by the number of operations. It is not an average over likely inputs or a claim that resizes are rare by chance. A single append still has worst-case O(n) time.

Save work credits

Another way to see the bound is to charge 3 units for each append: 1 for the new write and 2 saved toward copying. While an array of capacity c goes from half full to full, its c/2 appends save c units. Those credits pay for copying c entries at the next doubling. Early saved credits cover the initial small resize. The charge stays constant even when the actual cost jumps.

Avoid fixed-step growth

Growing by a fixed number creates a very different sum. From capacity 4, adding 4 slots each time while appending 100 elements copies

4+8+⋯+96=1200

Doubling from capacity 4 copies only 4+8+16+32+64=124. For 1000 elements the totals are 124500 and 1020. Fixed-step growth repeatedly copies an array only a little larger than before, giving O(n2) total work and O(n) amortized work per append.

Any fixed growth factor greater than 1 gives amortized constant-time append. A factor of 1.5 saves unused space compared with doubling but copies more often. CPython grows a list proportionally too, with roughly one-eighth extra space plus a small constant, rather than following the textbook doubling sequence exactly.

Leave a gap before shrinking

Suppose size and capacity are both 8. Append once: copy 8 entries into capacity 16 and reach size 9. Pop once: return to size 8. If half-full storage immediately shrinks, copy 8 entries back into capacity 8. Alternating these operations now copies a linear number of entries each time.

Instead, halve only at one-quarter occupancy. Capacity 16 then shrinks at size 4 to capacity 8, leaving it half full. Many appends are needed before growth; many deletions are needed before another shrink. With a fixed minimum capacity, end appends and pops remain amortized O(1).

Python list indexing and indexed assignment cost O(1). End append and pop cost amortized O(1); indexed insertion and removal also pay for suffix shifts, reaching O(n) at the front. A program that needs a bound on every operation can reserve capacity or use fixed-size storage to avoid a whole-array resize pause.

Key Takeaways

  • Amortized cost bounds a complete run, not a distribution of random inputs.
  • Doubling from capacity 1 makes fewer than 2n copies during n appends.
  • One append can be linear while appends are amortized constant time.
  • Fixed-step growth makes a long run of appends quadratic.
  • A fixed proportional growth factor trades copying frequency for spare memory.
  • Separate grow and shrink thresholds prevent repeated resize thrashing.
  • Strict per-operation timing needs more than an amortized guarantee.
3

Build linked lists and update their links safely

Linked lists grow by connecting nodes, so edits depend on which references are already available. Build a singly linked chain, handle its empty and one-element states, then add backward links and sentinels for local edits at either end. A circular chain supports repeated turns with a change of starting point. Tracing every changed reference shows why some operations stay constant time while others need a walk.

3.1 A singly linked list implementation

A singly linked list stores its sequence in nodes connected by next references. Keeping both head and tail makes adding at either end cheap, but it does not make removing at either end equally cheap.

Build a chain

Each node holds an element and its successor. The final node points to None. An empty list has no first or last node, so both head and tail are None and size is zero.

class _Node:
    __slots__ = ("element", "next")

    def __init__(self, element, next_node=None):
        self.element = element
        self.next = next_node

class SinglyList:
    def __init__(self):
        self.head = self.tail = None
        self.size = 0

    def add_first(self, value):
        node = _Node(value, self.head)
        self.head = node
        if self.size == 0:
            self.tail = node
        self.size += 1

    def add_last(self, value):
        node = _Node(value)
        if self.size == 0:
            self.head = node
        else:
            self.tail.next = node
        self.tail = node
        self.size += 1

    def delete_first(self):
        if self.size == 0:
            raise IndexError("list is empty")
        value = self.head.element
        self.head = self.head.next
        self.size -= 1
        if self.size == 0:
            self.tail = None
        return value

    def __iter__(self):
        walk = self.head
        while walk is not None:
            yield walk.element
            walk = walk.next

__slots__ is optional; it reduces per-node attribute storage. It does not change the links or the algorithms.

Preserve the old chain before replacing a link

For 8 → 3 → 5, adding 1 first creates a node pointing to the old head, then makes that node the new head. The chain becomes 1 → 8 → 3 → 5. Assigning the new head before saving the old one would lose the only entry point to the old chain.

Insertion after a held node follows the same order:

new = _Node(value, node.next)
node.next = new
if self.tail is node:
    self.tail = new
self.size += 1

The new node first remembers the successor. Only then does the predecessor point to the new node. Updating the tail when inserting after the old tail keeps later tail insertions correct.

Deleting the head also has an empty-state case. When its successor is None, the removed node was the only element. Leaving tail unchanged would keep a reference to a node no longer in the sequence, and a later append could attach to that detached node.

Include the cost of finding a position

Adding or deleting at the head costs O(1). Adding at the tail costs O(1) with the tail reference. Removing the tail still needs its predecessor: walk from the head to find the node whose next is the old tail. That takes O(n) in the worst case.

Likewise, inserting after a node already held costs O(1), but insertion at index i first locates the predecessor and costs O(i+1). An array with spare capacity instead shifts the suffix in O(n−i+1). The linked list favors the front; the array favors the back.

Traversal and unsorted value search cost O(n). A singly linked list is therefore a good stack at its head, or a queue that adds at the tail and removes at the head. Both access patterns avoid predecessor searches.

Key Takeaways

  • An empty head-and-tail list keeps both references at None.
  • Save the successor before replacing a link.
  • Head insertion and removal are constant time; tail insertion needs a tail reference.
  • Tail removal still needs a linear predecessor search.
  • Include position lookup when analyzing indexed edits.
  • A stack uses the head; a queue adds at the tail and removes at the head.

A second link changes what you can do with a node already in hand. Closing a chain into a circle changes how you move through repeated turns.

Edit a doubly linked list

A doubly linked node stores both prev and next. Given a real node, you can reach either neighbor directly. This permits constant-time deletion without searching for a predecessor.

Two sentinel nodes simplify the ends. A header sits before the first element and a trailer after the last. Neither counts as an element. Initially header.next is trailer, trailer.prev is header, and size is zero. Every real node has a neighbor on both sides, even when it is the only element.

These helpers operate on a list with those sentinels. The insertion helper receives adjacent nodes p and q; deletion receives a real node, never a sentinel.

class _DNode:
    def __init__(self, element, prev=None, next_node=None):
        self.element = element
        self.prev = prev
        self.next = next_node

# Methods inside the list class:
def _insert_between(self, value, p, q):
    node = _DNode(value, p, q)
    p.next = node
    q.prev = node
    self.size += 1
    return node

def _delete_node(self, node):
    value = node.element
    p, q = node.prev, node.next
    p.next = q
    q.prev = p
    self.size -= 1
    node.prev = node.next = None
    node.element = None
    return value

To insert at the front, use the header and its successor. At the back, use the trailer's predecessor and the trailer. The same insertion code handles an empty list because its sentinels are already adjacent.

For A ↔ B ↔ D, insert C by first giving C links to B and D, then setting B.next = C and D.prev = C. To delete A, connect header.next to B and B.prev to the header. Updating only one direction produces a list that may look correct forward but fail backward.

A held position makes local insertion, deletion, and one-step cursor movement O(1). Index access remains O(n), though a size-aware list can start from the nearer end. In size 10, index 8 is one backward link from the final element. Extra backward links cost storage and more updates per edit.

Close the final link

A circularly linked list makes the last node point to the first. In a nonempty list, storing only tail is enough to recover the head as tail.next. Rotating the first element to the back needs only:

tail = tail.next

No node moves and no link changes. The head is now the node after the new tail. For A → B → C → A with tail C, the new tail is A and the logical order becomes B, C, A.

A circular traversal stops after size nodes or upon returning to the start. Waiting for None would loop forever. An empty circular list needs a separate empty state, usually tail = None; the formula tail.next applies when nonempty.

Give tasks repeated turns

In round-robin scheduling, run the front task for one time slice. Remove it if complete; otherwise rotate it to the back. For A, B, and C needing 3, 1, and 2 slices, the execution order is A, B, C, A, C, A. B leaves after its first turn, so later rounds skip it. A circular list models the recurring order without moving every element in storage.

Key Takeaways

  • Backward links allow constant-time deletion of a held real node.
  • Sentinels give every real node two neighbors, including at the ends.
  • Insertion and deletion must repair both directions.
  • A held position is different from an index that must first be located.
  • In a nonempty circular list, tail.next is the head.
  • Rotation can change only the tail reference.
  • Circular traversal must stop by count or return to its starting node.
4

Use stacks, queues and deques to solve problems

Stacks, queues, and deques restrict access in ways that match recurring programming tasks. Choose the right end for each operation, trace the stored state, and apply the ordering to nested brackets, partial expression results, arrival order, and recent history. Circular indexing makes a queue work without shifts, while two-ended access supports buffers and rotation. The implementation determines the cost behind each shared interface.

4.1 Stacks for nested work and history

A stack exposes the most recently added unfinished item. This last-in, first-out order matches nested tasks: an inner task finishes before the outer task resumes.

Put the top at an efficient end

With a Python list, use the end as the top: append pushes, pop() removes, and stack[-1] peeks. Push and pop cost amortized O(1); peek costs O(1). Using insert(0, value) and pop(0) would shift the remaining elements on every change.

With a singly linked list, use the head as the top. Both push and pop are worst-case O(1) in the memory model, with no backing-array resize. Putting the top at its tail would make pop search for the predecessor.

An empty pop or peek is an error. An explicit exception keeps failure distinct from a legitimate stored None.

Match brackets with the last unmatched opener

Scan text from left to right. Push each opening bracket. At a closing bracket, require a nonempty stack whose top is the matching opener. After the scan, require an empty stack.

def balanced(text):
    openers = "([{"
    matching = {")": "(", "]": "[", "}": "{"}
    stack = []
    for char in text:
        if char in openers:
            stack.append(char)
        elif char in matching:
            if not stack or stack.pop() != matching[char]:
                return False
    return not stack

For "{[()()]}", each closer removes its matching top, leaving nothing at the end. In "([)]", ) meets [ on top, so matching fails immediately. In "(()", a remaining opener causes failure after the scan. In "())", the last closer finds an empty stack. Equal counts alone miss the nesting error in "([)]". Non-bracket characters, as in "a[b(c)d]e", are skipped.

Evaluate postfix expressions

A postfix operator comes after its operands. Push numbers. For an operator, pop the right operand first and the left operand second, compute, then push the result.

For 5 1 2 + 4 * + 3 -, begin with [5, 1, 2]. The + replaces 1 and 2 with 3, giving [5, 3]. Push 4; * replaces 3 and 4 with 12, giving [5, 12]. The next + gives [17]. Push 3 and subtract to obtain [14].

Operand order matters: the final step computes 17 - 3, not 3 - 17. For a valid binary postfix expression, every operator has two operands and exactly one result remains at the end. The stack holds partial results still needed by later operators.

Maintain two directions of history

A browser can use a back stack, a current page, and a forward stack. Visiting a new page pushes the current page onto back and clears forward. Back pushes the current page onto forward, then pops back to choose the page to display. Forward reverses those roles.

After visiting A, B, and C, Back displays B with A in back and C in forward. Opening D now puts B on back and clears C from forward. The new visit creates a new continuation of the history.

Undo actions, sequence reversal, backtracking, and the call stack use the same ordering. A call frame stays active until its function returns; a deeper call finishes before its caller continues. Very deep recursion can exhaust the call stack.

Key Takeaways

  • LIFO exposes the most recently pushed item.
  • Use a list end or a singly linked head as the top.
  • Bracket matching checks type, nesting order, and the final empty state.
  • In postfix evaluation, pop the right operand before the left.
  • A new browser visit clears the forward stack.
  • Empty pop and peek must report an error.

4.2 Queues without front shifts

A queue serves the oldest waiting element first. Adding at the back and removing at the front preserves arrival order, but the storage must support those ends efficiently.

Move the front index

A circular array queue stores capacity N, the first element's index front, and the number of elements size. Logical position k lives at (front + k) % N. The remainder wraps a physical index back to zero.

On enqueue, write at (front + size) % N and increment size. On dequeue, save and clear data[front], advance front modulo capacity, and decrement size. The other elements stay where they are.

These methods fit a class initialized with data = [None] * N, front = 0, and size = 0, where N is positive:

def enqueue(self, value):
    if self.size == len(self.data):
        self._resize(2 * len(self.data))
    slot = (self.front + self.size) % len(self.data)
    self.data[slot] = value
    self.size += 1

def dequeue(self):
    if self.size == 0:
        raise IndexError("queue is empty")
    value = self.data[self.front]
    self.data[self.front] = None
    self.front = (self.front + 1) % len(self.data)
    self.size -= 1
    return value

def _resize(self, capacity):
    old = self.data
    new = [None] * capacity
    for k in range(self.size):
        new[k] = old[(self.front + k) % len(old)]
    self.data = new
    self.front = 0

first() reads the front without changing it, after the same empty check. len() reports size and is_empty() tests size zero.

Trace wraparound and growth

With capacity 5, enqueue A, B, C, and D. Dequeue twice, returning A and B. Now front = 2, size = 2, and C and D remain in slots 2 and 3. Enqueue E at slot 4, F at slot 0, and G at slot 1. Physical storage is [F, G, C, D, E], but logical order is C, D, E, F, G.

Enqueueing H triggers growth to capacity 10. Copy in logical order into indices 0 through 4, reset front to 0, then write H at 5. Copying physical slots in order would incorrectly serve F and G before C.

Track size explicitly: the next write position equals front in both an empty and a full ring. An alternative design reserves one unused slot, but then usable capacity is one less than the array length.

Choose a linked or library queue

A singly linked queue enqueues at its tail and dequeues at its head. Both operations are worst-case O(1) in the model; removing the last item must clear both endpoint references. Reversing the ends makes dequeue search for the tail's predecessor.

For ordinary Python code, collections.deque supplies append and popleft with O(1) end costs. A list's pop(0) moves the remaining references. Emptying n elements that way moves (n−1)+(n−2)+⋯+1 references, giving O(n2) total work. A circular array with doubling gives amortized O(1) enqueue and O(1) dequeue when it does not shrink.

Queues fit print jobs, message buffers, and breadth-first exploration. queue.Queue adds locking and blocking operations for work passed between threads. A priority queue uses priority to choose what leaves; arrival order alone does not determine its next element.

Key Takeaways

  • FIFO removes elements in arrival order.
  • Circular storage moves the front index instead of shifting the sequence.
  • Enqueue uses (front + size) % capacity.
  • Resize copies logical queue order and resets front.
  • Size distinguishes a full ring from an empty ring.
  • A linked queue adds at the tail and removes at the head.
  • Repeated list.pop(0) makes draining a queue quadratic.

4.3 Deques for work at both ends

A deque, pronounced "deck," is a double-ended queue. It can add, inspect, and remove at either end, so it supports access patterns that need more freedom than a stack or queue.

Extend the end operations

The ADT offers add_first, add_last, delete_first, and delete_last, with first, last, is_empty, and len. Using one end for both insertion and removal gives a stack. Inserting at one end and removing at the other gives a queue. The noun deque names the collection; dequeue names the act of removing from a queue.

In a circular array of positive capacity N, a front insertion first computes front = (front - 1) % N, then writes the new element there and increments size. A back insertion writes at (front + size) % N. A back deletion uses (front + size - 1) % N before decreasing size. Front deletion clears the old front and advances it.

In Python, (0 - 1) % 5 is 4, which wraps backward correctly. In Java and C, the negative remainder requires (front - 1 + N) % N for this one-step move. Resizing must still copy elements in logical order. With proportional growth and safe shrink thresholds, end operations are amortized O(1).

A sentinel-based doubly linked list also supports every deque end operation in worst-case O(1). A singly linked list cannot give that bound for deleting the last element, because it lacks a backward link to the new tail.

Use Python's deque
from collections import deque

d = deque(["A", "B"])
d.append("C")       # A, B, C
d.appendleft("Z")   # Z, A, B, C
right = d.pop()      # returns C
left = d.popleft()   # returns Z

extend appends multiple values; extendleft repeatedly appends values at the left. For d = deque([3]), d.extendleft([1, 2]) gives [2, 1, 3] because 2 is added at the left after 1. Empty pop and popleft raise IndexError.

CPython implements a deque with doubly linked fixed-size blocks of 64 slots. End appends and pops touch an end block and sometimes add or remove a block; they never copy the whole collection. Indexing near the ends is constant time, but indexing the middle is O(n). A deque is therefore a poor replacement for a list when arbitrary indexed reads dominate.

Retain recent items and rotate turns

A bounded deque automatically discards from the opposite end when an append would exceed its limit:

d = deque(maxlen=3)
for value in [1, 2, 3, 4, 5]:
    d.append(value)
# d holds 3, 4, 5

This fits a recent-event history or a sliding window: new readings enter at the back and old readings expire at the front. A bounded undo history can pop recent actions while dropping the oldest when full.

Positive rotation moves right. Rotating [1, 2, 3, 4, 5] by 2 gives [4, 5, 1, 2, 3]; rotating the original by -1 gives [2, 3, 4, 5, 1]. One left rotation sends the front item to the back for round-robin turns.

To check a palindrome, load its characters into a deque and compare popleft() with pop() until at most one remains. For "level," compare l with l, then e with e; the middle v needs no partner. "robot" fails when r and t differ. Each character is removed at most once, so the whole check is O(n).

Java's ArrayDeque implements a deque with circular-array storage; LinkedList provides deque operations with a doubly linked list.

Key Takeaways

  • A deque supports insertion and removal at both ends.
  • Circular arrays and doubly linked lists support efficient deque operations.
  • Python deque appends and pops do not copy the whole collection.
  • Middle indexing in a deque is linear.
  • Bounded deque appends discard from the opposite end.
  • Positive rotation moves items right; negative rotation moves them left.
5

Choose and justify the right linear structure

A useful structure makes the program's frequent work cheap while meeting its storage and timing needs. Compare operations by position, include the cost of locating a node, and distinguish a worst-case bound from an amortized one. Then turn concrete requirements into an ordering contract and an implementation choice. Memory overhead and locality explain why equal asymptotic bounds can still lead to different measured speeds.

5.1 Compare costs with the access position included

An operation name is not enough to predict cost. State where the operation acts, how the position is supplied, and whether the bound applies to one operation or a whole run.

Compare sequence implementations

The table uses n for size. A singly linked list keeps both head and tail; a doubly linked list keeps endpoints or sentinels. Dynamic-array end changes have amortized bounds.

OperationDynamic arraySingly linked listDoubly linked list
Read arbitrary indexO(1)O(n)O(n)
Add at frontO(n)O(1)O(1)
Remove at frontO(n)O(1)O(1)
Add at backAmortized O(1)O(1)O(1)
Remove at backAmortized O(1)O(n)O(1)
Search unsorted valuesO(n)O(n)O(n)

Middle edits need a second question: do you already hold the position? A dynamic array shifts a suffix, reaching O(n). A doubly linked list edits next to or deletes a held node in O(1). A singly linked list needs the predecessor for deletion or insertion before a node. If an index or value must first be located, that search can make the complete linked edit O(n).

A sorted array supports binary search in O(log⁡n), but insertion into sorted order still moves entries. Direct indexing, value lookup, and maintaining sorted order are separate tasks.

Read the guarantee correctly

Worst-case O(1) bounds each operation in the model. Amortized O(1) bounds total work across a run, allowing individual linear resizes. A linked stack uses its head; a linked queue uses tail insertion and head deletion; a doubly linked deque uses both ends. These give worst-case constant-time link work.

A list-backed stack or resizing circular queue gives amortized constant-time end changes. CPython's block-linked deque gives constant-time end appends and pops without whole-collection copying. For a strict timing requirement, avoiding algorithmic resizing is useful, though actual elapsed time also depends on allocation and the runtime.

Include storage and real speed

A dynamic array reserves spare slots. Right after doubling, roughly half its capacity is unused, but its slots need no per-element link fields. A singly linked node adds one reference and a doubly linked node adds two, plus each node's separate-object overhead. In a referential array, the elements themselves also live outside the slot block; compare like-for-like stored objects when measuring memory.

Contiguous slots improve locality and reduce allocation frequency. Scattered nodes may require more cache misses and one allocation per element. Equal big-O bounds can therefore have different measured times. A sequential scan of a dynamic array is often faster than traversing a linked list, though both are linear.

Use timeit when those differences matter. Measure the operations the program actually performs at relevant collection sizes. Constructing data inside one timed case but outside another would compare setup work as well as the intended operation.

Key Takeaways

  • Index access, endpoint changes, and value search are different operations.
  • Linked middle edits are constant time only after the needed position is available.
  • A singly linked tail reference does not make tail deletion constant time.
  • Amortized bounds allow an occasional linear resize.
  • Arrays trade spare slots for locality; nodes trade link storage for local edits.
  • Measure representative workloads when constant factors matter.

5.2 Choose from the operations a program performs

Choose a structure by describing the program's work in terms of operations. A familiar class name becomes useful evidence only after you connect it to the access pattern.

Turn requirements into an access pattern
  1. List the reads, additions, removals, and searches, with their approximate frequency.
  2. Identify the position each uses: arbitrary index, front, back, or a node already held.
  3. Decide whether occasional resize pauses are acceptable and how large the collection may become.
  4. Choose the ADT that matches the ordering, then an implementation with suitable costs.
  5. Justify the frequent operations with explicit bounds.

For example, "remove the oldest request" means FIFO access. "Read measurement number 400" means indexed access. "Remove the item under the cursor" describes a held position only if the cursor actually retains a node reference.

Match common workloads
Program behaviorSuitable structureReason
Undo newest actionList-backed stackEnd push and pop are amortized O(1)
Serve arrivals oldest firstcollections.deque as a queueAppend and popleft are O(1)
Append readings and read by day numberDynamic arrayIndexed reads are O(1); append is amortized O(1)
Move a cursor one place and edit thereDoubly linked listLocal movement and held-node edits are O(1)
Keep a fixed window without resizingFixed circular bufferEndpoint updates take O(1) within reserved storage

A bounded undo history adds an operation absent from an unlimited stack: discard the oldest action when the limit is reached. deque(maxlen=100) can drop from the old end while appending at the recent end. The same structure can still pop the most recent action.

Compare the whole workload

Suppose an application stores n readings, then performs m arbitrary indexed lookups. A dynamic array takes O(n+m) total time for the appends and reads. A linked list may take O(n+mn) because each lookup can traverse a linear number of nodes. Cheap linked insertion does not compensate for a much more frequent slow read.

A playlist with a retained node cursor has a different pattern: next, previous, insert beside the cursor, and delete the current song. A doubly linked list gives constant-time local work. If the interface instead repeatedly asks for a song by number, those indexed searches must be counted too.

Match the timing and retention rules

For a monitor holding the last 60 readings, a bounded deque handles automatic expiration. A fixed circular buffer of capacity 60 makes the storage limit explicit and avoids resizing. When full, its insertion behavior must implement the retention rule, replacing the oldest entry and advancing front.

For recurring turns, a circular list rotates by changing its tail reference, while a deque supports end-to-end rotation. Select this behavior when participants return for more turns; a completed task must leave the cycle.

Write a defensible reason

"Requests arrive continuously and the oldest is served first. A deque gives constant-time append and popleft; using list.pop(0) would shift the waiting requests after every service." This names the ordering, the implementation, and the cost that matters.

A lookup by customer ID is a search by key, not by position. Unsorted linear structures need O(n) search. A sorted array permits O(log⁡n) lookup but pays O(n) to maintain order on changes. Frequent key lookups with frequent updates usually call for a hash table or search tree.

Key Takeaways

  • List the frequent operations and how each position is obtained before choosing.
  • Choose the ordering contract first, then its implementation.
  • Include lookup work when comparing total workload costs.
  • Bounded history needs efficient access to both recent and oldest items.
  • Fixed buffers avoid resizing and need a clear full-buffer policy.

Linear Data Structures examples

5 Walkthroughs

1

Connect an interface to its memory layout

11 steps
Specify a stack, locate array entries, and trace shared references before comparing storage costs.
  1. 1
    IntroductionFollow one collection through two views

    Suppose a program needs a collection whose newest item is removed first. Begin by describing that behavior, then ask how the items can live in memory.

    Those are separate decisions. A public operation tells the program what to expect (the ADT contract); array slots or linked nodes determine the steps taken underneath. You will use a small stack to connect behavior, hidden state (kept valid by a representation invariant), and operation cost.

  2. 2
    ExplanationDescribe what pop promises

    For a stack, push(e) adds at the top and pop() removes and returns the most recent remaining item. top() reads that same item without removing it.

    A complete specification also covers failure: pop and top on an empty stack raise an exception. The contract says what the caller receives and how the state changes, without requiring an array or a node anywhere in that description.

  3. 3
    ExampleTrace a public interface

    Push "note", then "send". The stack's logical order is note below send. Calling top() returns "send" and leaves two elements. Calling pop() returns "send" and leaves one.

    A list-backed implementation can use append and end pop internally. A linked implementation can use head insertion and removal. The same trace works through either public interface, even though their stored states differ.

  4. 4
    Key InsightKeep the state valid

    A representation invariant describes a valid internal state. For a head-and-tail linked stack, empty means both endpoints are None, and size must equal the number of reachable elements.

    A method can return the right value and still break this rule. Removing the only node but leaving tail on that removed node creates a failure for later operations. Inspect the new state as well as the returned result.

  5. 5
    ChallengeSeparate a contract from storage

    A stack class replaces its Python list with singly linked nodes. The operation names, results, and error behavior stay the same. Has the ADT changed? What may change for an individual push?

    ---reveal---

    The ADT is unchanged because its promised behavior is preserved. The data structure has changed. A list-backed push may occasionally resize, while linked head insertion uses a fixed number of link updates in the memory model.

  6. 6
    ExplanationCalculate an address directly

    An array reserves equal-size slots in one contiguous block. Slot i starts at the base address plus i slot widths:

    start+i×slot size

    For 8-byte slots starting at 2000, index 7 is at 2056. Any valid index needs one multiplication and one addition, so array indexing is constant time in the model. Reaching a later index does not require visiting earlier slots.

  7. 7
    ExampleSkip whole rows, then columns

    A row-major table stores one complete row after another. With 5 columns, reaching row 2 skips 10 slots. Reaching column 3 then skips 3 more, for a flat offset of 13 slots.

    For 8-byte values starting at address 1000, the address is 1000+13×8=1104. The column count supplies the row width; the number of rows does not belong in that multiplier.

  8. 8
    ExampleTrace references instead of copying objects

    The expression [[0] * 3] * 3 makes one inner list, then repeats references to it. Assigning grid[0][0] = 1 changes that one object, so all three row views show [1, 0, 0].

    Use [[0] * 3 for _ in range(3)] for independent rows. Each loop iteration constructs a different inner list. The outer array still stores references, but those references now identify separate objects.

  9. 9
    ChallengeFind a row-major position

    A flat table has 4 columns of 8-byte values and starts at address 600. What is the address of zero-based position (2, 1)?

    ---reveal---

    Skip two rows of four values and one more value: 9 slots. The byte offset is 9×8=72, so the address is 672. Using 2 as the row width would skip too few entries; every preceding row contains all 4 columns.

  10. 10
    ChallengeConnect storage to the same interface

    Two sequence classes both offer get(i). One stores contiguous slots; the other stores a next-linked chain. Why can the same operation have different costs, and why can their complete scans differ in real speed?

    ---reveal---

    The interface specifies the result, not the representation. Array get calculates an address; linked get follows links. Both full scans are linear, but contiguous slots often share cache loads, improving locality.

  11. 11
    RecapRead the promise and the representation

    When you meet a collection, identify its public behavior and then inspect how the stored state supports it. A method's result, failure behavior, and invariant belong in that check.

    For performance, locate the work: address arithmetic, reference traversal, or copying. Sharing a public interface does not make two implementations equally fast, and copying references does not make independent copies of mutable objects.

2

Build an array that grows without wasteful copying

16 steps
Shift safely, trace doubling, and compare complete operation runs with different resize policies.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate two reasons an array does work
  2. 2
    ExampleOpen a gap from the back
  3. 3
    ExplanationCount a deletion separately
  4. 4
    ChallengeCount the moving suffix
  5. 5
    ExplanationKeep two counters with different meanings
  6. 6
    ExampleAllocate, copy, replace, append
  7. 7
    ExampleContinue the same growth trace
  8. 8
    ChallengeCheck the public bounds after growth
  9. 9
    ExampleCount sixteen appends as one run
  10. 10
    Key InsightUse the sum, not the number of resizes
  11. 11
    AnalogySet aside credits for the next copy
  12. 12
    ChallengeCompare different growth policies
  13. 13
    ExampleMake a bad shrink rule thrash
  14. 14
    TipLeave room between resize thresholds
  15. 15
    ChallengeCombine shifts and resize guarantees
  16. 16
    RecapAttach the bound to the work being counted
3

Trace linked edits without losing nodes

14 steps
Build forward links, repair backward links, and rotate a circular list while checking its invariants.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep the references needed for the next step
  2. 2
    ExplanationDescribe the empty and nonempty states
  3. 3
    ExampleInsert before changing head
  4. 4
    ExampleAppend and then remove at the head
  5. 5
    ChallengeRepair an empty-state bug
  6. 6
    Key InsightA tail reference is not a backward link
  7. 7
    ExplanationGive real endpoints neighbors
  8. 8
    ExampleInsert C between B and D
  9. 9
    ExampleDelete through both neighbors
  10. 10
    ChallengeSpot a one-direction repair
  11. 11
    ExampleRotate a circular list without relinking
  12. 12
    TipStop a circular traversal deliberately
  13. 13
    ChallengeInclude location work in a local edit
  14. 14
    RecapMatch the links to the work
4

Use access order to solve sequence problems

19 steps
Match brackets, evaluate postfix, preserve FIFO through wraparound, and retain recent items with a deque.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose which item should be accessible
  2. 2
    ExplanationPlace a stack top where changes are cheap
  3. 3
    ExamplePush the open brackets
  4. 4
    ExampleClose each group in nesting order
  5. 5
    ChallengeFind the first nesting failure
  6. 6
    ExampleKeep partial postfix results on a stack
  7. 7
    ChallengePreserve operand direction
  8. 8
    ConnectionMove history between two stacks
  9. 9
    ExplanationServe the front without shifting
  10. 10
    ExampleLet the physical slots wrap
  11. 11
    ExampleGrow from the logical front
  12. 12
    ChallengeTranslate a wrapped queue
  13. 13
    TipUse the right linked endpoints
  14. 14
    ExplanationAdd the other two endpoint operations
  15. 15
    ExampleExpire the oldest automatically
  16. 16
    ExampleRotate and compare opposite ends
  17. 17
    ChallengeFollow bounded retention from both ends
  18. 18
    ChallengeChoose ordering and retention together
  19. 19
    RecapLet the next-needed item choose the end
5

Justify a structure using the complete workload

10 steps
Compare positions, timing guarantees, and operation frequency to make a concrete implementation choice.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTurn a class preference into a cost argument
  2. 2
    ExplanationCompare the exact access requested
  3. 3
    ChallengeUnpack a vague insertion claim
  4. 4
    Key InsightChoose the guarantee the program needs
  5. 5
    ExampleCount an indexed archive workload
  6. 6
    ExampleGive a cursor its own position
  7. 7
    ExampleMake a fixed retention rule explicit
  8. 8
    ChallengeJustify FIFO storage
  9. 9
    ChallengeRecognize a requirement that changes the choice
  10. 10
    RecapState a reason that another developer can check

Linear Data Structures practice questions

50 Practice Questions in 5 sets

Set 1: Interfaces, memory, and array operations10 Practice Questions

Question 1 of 10

A packed array has 14 stored elements and spare capacity. How many existing elements move when an element is inserted at index 9?
  1. 5
  2. 4
  3. 6
  4. 9
Show answerHide answer
Answer: A
The old elements at indices 9 through 13 each move one place right, for 5 moves. The new element also needs a write, but it is not an existing element being moved. Counting only indices after 9 would give 4 and leave the old index-9 value without a new position.

Question 2 of 10

A stack changes its internal storage from an array to linked nodes while keeping the public operations and their behavior. What has changed?
  1. The ordering rule defining the ADT.
  2. The data structure implementing the ADT.
  3. The meaning of the public pop operation.
  4. The values accepted by the stack interface.
Show answerHide answer
Answer: B
The concrete storage has changed, so the data structure is different. The stack ADT still promises the same operations and LIFO behavior. A change of representation can change performance without changing what a successful pop returns.

Question 3 of 10

An array starts at byte address 3200 and stores 8-byte values. What is the address of index 6?
  1. 3240
  2. 3206
  3. 3256
  4. 3248
Show answerHide answer
Answer: D
Index 6 lies six slots after the start, giving 3200 + 6 × 8 = 3248. Index 0 occupies the starting slot, so there is no extra slot to add. Counting index 6 as the seventh offset would incorrectly give 3256.

Question 4 of 10

A stack may store None. Its current pop method returns None both after removing a stored None and when empty. What change makes failure distinguishable while preserving stored values?
  1. Remove None values during every push.
  2. Return None without changing the stack.
  3. Raise an exception on an empty pop.
  4. Use the current size as every pop result.
Show answerHide answer
Answer: C
An exception gives the empty case a separate failure path while allowing None to remain an ordinary element. Banning None would change which values the stack supports, even though the problem only asks to distinguish failure. A successful pop must still remove and return the stored top value.

Question 5 of 10

A flat row-major table has 7 columns of 4-byte values and starts at address 800. What is the address of zero-based position (3, 5)?
  1. 864
  2. 896
  3. 904
  4. 940
Show answerHide answer
Answer: C
Three complete rows contain 21 values, and column 5 adds five more slots. The offset is 26 × 4 = 104 bytes, so the address is 904. The address 896 is only 24 slots from the start and stops two values before the requested position.

Question 6 of 10

A packed array stores [7, 12, 19, 25] with spare capacity. An insertion at index 1 shifts right by visiting source indices 1, 2, 3 in that order. What old value remains at index 4 after those shifts?
  1. 12
  2. 19
  3. 25
  4. 7
Show answerHide answer
Answer: A
The first copy overwrites index 2 with 12. The next copies that same 12 into index 3, and the last copies it into index 4. The value 25 would survive there only if the shift started at the back, before its source slot was overwritten.

Question 7 of 10

A dynamic array has size 7 and capacity 12. Its get method accepts every index below capacity. What is the greatest valid nonnegative index, and what is wrong with the check?
  1. 7; it hides the last element.
  2. 11; it excludes reserved slots.
  3. 12; it rejects the final slot.
  4. 6; it exposes unused slots.
Show answerHide answer
Answer: D
Stored elements occupy indices 0 through 6 because size is 7. A read must be checked against size, so accepting indices 7 through 11 exposes storage that is not part of the sequence. Capacity describes reserved slots and does not extend the logical list.

Question 8 of 10

What does rows contain after this code?

rows = [[0] * 2] * 4
rows[2][1] = 9
  1. [[0, 0], [0, 0], [0, 9], [0, 0]]
  2. [[0, 9], [0, 9], [0, 9], [0, 9]]
  3. [[9, 0], [9, 0], [9, 0], [9, 0]]
  4. [[0, 0], [0, 0], [9, 0], [0, 0]]
Show answerHide answer
Answer: B
All four outer entries refer to the same inner list, so changing its index 1 appears in every row. Index 2 chooses a reference to that shared object; it does not create a separate row. Only the third row would change if the rows had been constructed independently.

Question 9 of 10

An ordered packed array currently holds 18 elements. It deletes index 6, then inserts a new element at index 4. No resize occurs. How many existing-element moves occur in total?
  1. 23
  2. 24
  3. 25
  4. 26
Show answerHide answer
Answer: B
The deletion moves 18 − 6 − 1 = 11 elements and leaves size 17. The insertion then moves 17 − 4 = 13 elements, for 24 total. Keeping the original size for the insertion would count one element that has already been removed and incorrectly give 25.

Question 10 of 10

A dynamic array has size 6 and capacity 8. It inserts X at index 2, deletes index 5, then appends Y, Z, and W. It doubles only when full and never shrinks. How many existing entries are copied during resizes, and what are the final size and capacity?
  1. 8 copies; size 9, capacity 16.
  2. 6 copies; size 9, capacity 12.
  3. 8 copies; size 10, capacity 16.
  4. 16 copies; size 9, capacity 16.
Show answerHide answer
Answer: A
Insertion raises size to 7 and deletion returns it to 6. Y and Z fill the remaining slots; appending W copies the 8 stored entries into capacity 16 and reaches size 9. Counting 16 copies confuses the new capacity with the number of entries actually copied.
Set 2: Growth policies and linked-list changes10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A dynamic array contains 9 elements in 16 slots. How many reserved slots are currently unused?
  1. 7
  2. 8
  3. 9
  4. 16
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does an amortized constant-time append guarantee for n appends starting from an empty doubling array?
  1. Constant work for each individual append.
  2. Linear work for each individual append.
  3. Linear total work across the run.
  4. Constant total work across the run.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Starting empty at capacity 1, an array doubles whenever full and never shrinks. How many old-entry copies occur during 13 appends?
  1. 12
  2. 13
  3. 31
  4. 15
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A singly linked list has one node, with both head and tail referring to it. After delete_first removes that node, what endpoint state must be stored?
  1. head is None; tail keeps the node.
  2. head is None and tail is None.
  3. head keeps the node; tail is None.
  4. head and tail keep the old node.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A singly linked list keeps head and tail but no backward links. Why is removing its last node linear in the worst case?
  1. The old tail must be found from head.
  2. The new tail must be found from head.
  3. Every remaining node must be copied.
  4. Every next link must be set to None.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A doubly linked list contains P ↔ R between sentinels. A new Q already has prev = P and next = R. What remaining link updates complete the insertion?
  1. P.prev = Q and R.next = Q.
  2. Q.prev = R and Q.next = P.
  3. P.next = R and R.prev = P.
  4. P.next = Q and R.prev = Q.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An array doubles when full and halves immediately when a pop leaves it half full. It starts at size 16, capacity 16. What are the total resize copies and final capacity after append, pop, append, pop?
  1. 64 copies; capacity 16.
  2. 32 copies; capacity 16.
  3. 48 copies; capacity 32.
  4. 64 copies; capacity 32.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Tasks L, M, and N need 2, 3, and 1 time slices. A round-robin queue starts in that order, runs one slice per turn, removes completed tasks, and returns unfinished tasks to the back. What is the execution order?
  1. L, M, N, L, M, N.
  2. L, L, M, M, M, N.
  3. L, M, N, L, M, M.
  4. L, M, N, M, L, M.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A list is singly linked with head and tail. Code holds a middle node p and inserts a node after p, then removes the final node. It has no other node references. What is the worst-case total time in the original size n?
  1. O(1), because both positions are held.
  2. O(n2), due to two separate traversals.
  3. O(log⁡n), because the list gets shorter.
  4. O(n), due to the tail removal.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An empty array starts at capacity 3 and adds exactly 3 slots whenever full. How many existing entries are copied while appending 15 elements?
  1. 12
  2. 27
  3. 30
  4. 45
Show answerHide answer

Save this lesson to see this answer.

Set 3: Trace stacks, queues, and two-ended buffers10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A stack receives push("oak"), push("elm"), pop(), push("fir"). What does top() return?
  1. "oak"
  2. "elm"
  3. An empty-stack error
  4. "fir"
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

While checking the text "{([])}]", at what point is imbalance first detected?
  1. At ), with [ still at the top.
  2. At the final ], with an empty stack.
  3. At }, with ( still at the top.
  4. After the scan, with { left on top.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What value does the postfix expression 18 6 2 - / produce?
  1. 4.5
  2. -4.5
  3. 1.5
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A circular queue has capacity 8, front 6, and size 3. No resize is needed. At what physical index will enqueue write the next element?
  1. 0
  2. 2
  3. 1
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A deque starts as [2, 4, 6, 8]. It rotates by -1, then appendleft(1) and pop() are called. What remains, from left to right?
  1. [1, 4, 6, 8]
  2. [1, 8, 2, 4]
  3. [4, 6, 8, 1]
  4. [1, 2, 4, 6]
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A circular queue has capacity 6, front 4, size 4, and physical storage [R, S, None, None, P, Q]. It dequeues once, enqueues T, U, and V, then enqueues W, doubling only when full. What are its final logical order and front?
  1. R, S, T, U, V, Q, W; front 0.
  2. Q, R, S, T, U, V, W; front 0.
  3. Q, R, S, T, U, V, W; front 5.
  4. Q, R, S, T, U, W, V; front 0.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A browser starts on Home with empty history. It visits Docs, then FAQ, presses Back, visits Search, presses Back, then presses Forward. What is the current page, and what is in the forward stack?
  1. FAQ; the forward stack holds Search.
  2. Docs; the forward stack holds Search.
  3. Search; the forward stack holds FAQ.
  4. Search; the forward stack is empty.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Let d = deque([10, 20, 30], maxlen=4). After d.appendleft(5), d.append(40), d.rotate(1), and d.popleft(), what remains?
  1. [5, 10, 20]
  2. [20, 30, 40]
  3. [10, 20, 30]
  4. [40, 10, 20]
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An evaluator scans 8 3 2 * - 5 +. A bug reverses the left and right operands for every operator. What result does the buggy evaluator produce?
  1. 7
  2. 3
  3. -7
  4. -3
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A singly linked list has head and tail references. What deque endpoint operation still needs linear time in the worst case?
  1. Delete the last element.
  2. Delete the first element.
  3. Insert at the first position.
  4. Insert after the last node.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Find invariant failures and hidden costs10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

In a doubly linked list with header and trailer sentinels, what is size when the list contains no real elements?
  1. 1
  2. 2
  3. 0
  4. -1
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A circular singly linked list has tail Z and links X → Y → Z → X. After tail = tail.next, what are the head and tail?
  1. Head X, tail Y.
  2. Head Y, tail X.
  3. Head Z, tail X.
  4. Head Y, tail Z.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A ring queue stores only front and next-write indices and allows all slots to be used. Both indices are equal. What extra state can distinguish empty from full without reducing usable capacity?
  1. An explicit element count.
  2. The value in the front slot.
  3. The number of backing slots.
  4. The index of the first slot.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

An array doubles when full and shrinks from capacity 64 to 32 when size reaches 16. How many additional appends fit before another growth is needed?
  1. 15
  2. 17
  3. 32
  4. 16
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A singly linked list stores A → B → C, with tail C and size 3. Code inserts D after C by changing C.next, but forgets to update tail. A later add_last(E) uses the usual tail-based algorithm. What chain is reachable from head, and what size counter results?
  1. A → B → C → D → E; size 5.
  2. A → B → C → E; size 4.
  3. A → B → D → E; size 5.
  4. A → B → C → E; size 5.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A doubly linked list stores A ↔ B ↔ C. Deleting B updates A.next to C but leaves C.prev unchanged. A subsequent insertion of X immediately before C obtains its predecessor from C.prev and uses the usual insertion helper. What forward and backward behavior results around C?
  1. Forward from A reaches X; backward from C skips X.
  2. Both directions show A, X, C in matching order.
  3. Forward from A skips X; backward from C reaches X then B.
  4. Both directions still show A, B, C in matching order.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A full circular queue has capacity 5, front 3, and logical order J, K, L, M, N. During growth, code copies physical slots 0 through 4 directly into the new array and sets front to 0. What order will dequeues return?
  1. L, M, N, J, K.
  2. J, K, L, M, N.
  3. M, N, J, K, L.
  4. K, L, M, N, J.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A program inserts n values at the front of an initially empty dynamic array, then reads every value by index once. What is the total worst-case growth order, with proportional resizing?
  1. O(n), since both phases visit n values.
  2. O(n2), dominated by insertion shifts.
  3. O(nlogn), due to proportional growth.
  4. O(n3), since every read shifts entries.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A grow-only array starts empty at capacity 1. Policy P doubles; policy Q adds one slot whenever full. For n appends, what are the total work orders, including copying and new writes?
  1. P: O(nlogn); Q: O(n2).
  2. P: O(n); Q: O(n).
  3. P: O(n2); Q: O(n2).
  4. P: O(n); Q: O(n2).
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A palindrome check removes one character from each end of a deque until at most one remains. What happens for the word "refer"?
  1. It matches two pairs and leaves one character.
  2. It matches three pairs and leaves none.
  3. It fails when the middle character has no pair.
  4. It matches one pair and leaves three characters.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Choose structures for complete workloads10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A service must handle waiting jobs in their arrival order. What ADT directly matches that removal rule?
  1. A LIFO stack.
  2. A priority queue.
  3. A key-based set.
  4. A FIFO queue.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Two implementations each scan n elements in O(n) time. Why might the contiguous array scan run faster than a linked-list scan?
  1. Nearby slots can share cache loads.
  2. Each linked step rescans the chain.
  3. Array scans skip many comparisons.
  4. Linked nodes copy each value on access.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A program appends readings and often retrieves a reading by its zero-based sample number. What implementation gives constant-time indexed reads and amortized constant-time appends?
  1. A singly linked list.
  2. A doubly linked list.
  3. A dynamic array.
  4. A block-linked deque.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

An editor stores n items in a doubly linked list. In mode P, each of n edits arrives as an arbitrary index near the middle. In mode Q, a real node cursor is already held and n edits or one-step moves occur next to it. What are the worst-case total bounds, excluding initial construction?
  1. P: O(n); Q: O(n).
  2. P: O(n2); Q: O(n).
  3. P: O(n2); Q: O(n2).
  4. P: O(n); Q: O(n2).
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A monitor uses an 8-slot circular buffer and must never resize after startup. It currently holds readings 11 through 18 in arrival order, with front 6. It adds 19, 20, and 21, retaining only the newest eight readings. What are the final front, oldest reading, and per-update work bound?
  1. Front 2; oldest 14; O(1) work.
  2. Front 1; oldest 14; O(1) work.
  3. Front 1; oldest 15; O(1) work.
  4. Front 1; oldest 14; O(n) work.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An initially empty collection receives n appends, then n reads at independently requested indices. What are worst-case total bounds for a dynamic array and a singly linked list with a tail?
  1. Array O(n2); linked list O(n).
  2. Array O(n); linked list O(n).
  3. Array O(n); linked list O(n2).
  4. Array O(n2); linked list O(n2).
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An undo history keeps at most four actions, appending new actions at its recent end and removing from that end to undo. Starting empty, it records H, I, J, K, and L, undoes twice, then records M. What actions remain from oldest to newest?
  1. I, J, M.
  2. H, I, M.
  3. J, K, M.
  4. I, J, K, M.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A doubling array starts empty at capacity 1. After reaching size 32, the program appends once and then pops once. It shrinks only at one-quarter occupancy. How many entries are copied during these final two operations, and what capacity remains?
  1. 64 copies; capacity 32.
  2. 32 copies; capacity 32.
  3. 0 copies; capacity 64.
  4. 32 copies; capacity 64.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An unsorted sequence must find a record by its customer ID. Why does constant-time array indexing not make this lookup constant time?
  1. The search must shift records to preserve their order.
  2. A tail reference reveals only the final record's position.
  3. The ID does not supply the record's array position.
  4. The records must be copied before their IDs can be read.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A sorted dynamic array holds n records. A cycle searches for a key, then inserts a new record near the middle while keeping sorted order. A doubly linked alternative starts each cycle with only head and tail. What is the worst-case time per cycle for each?
  1. Array O(log⁡n); linked list O(1).
  2. Array O(n); linked list O(n).
  3. Array O(log⁡n); linked list O(n).
  4. Array O(n); linked list O(1).
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

63 Key Terms, each with its definition

A

Abstract data type
An abstract data type specifies the operations a collection supports and their behavior without prescribing how its data is stored.
A stack ADT promises newest-first removal whether its implementation uses an array or linked nodes.
Access pattern
An access pattern describes which operations a program performs, how often it performs them, and which positions or endpoints they touch.
Frequent indexed reads and occasional appends suggest a different choice from frequent front removals.
Address
An address is a number identifying a memory location; a known address lets the memory model read or write a fixed-size word in constant time.
The address of array index 0 is the start of its reserved block, before adding any slot offset.
Aliasing
Aliasing occurs when two or more references identify the same object, so a mutation through one reference is visible through the others.
Repeating a row list with multiplication creates aliasing instead of independent copies of the row.
Amortized cost
An amortized cost bounds the worst-case total work of an operation sequence divided by its length, without averaging over random inputs.
A doubling array has amortized constant-time appends even though a particular append can copy all entries.

B

Binary search
A binary search repeatedly halves a sorted search interval, using comparisons to locate a value in logarithmic time on an array.
A sorted array speeds up lookup with binary search but still shifts entries when inserting in order.
Bounded deque
A bounded deque has a maximum length and, when an append exceeds that limit, automatically discards an element from the opposite end.
A bounded deque of length 4 retains only the newest four events after repeated right appends.
Bracket matching
Bracket matching checks that each closer pairs with the latest unmatched opener of the correct type and that no openers remain afterward.
The text "([)]" fails bracket matching despite containing equal counts of each bracket type.

C

Call stack
A call stack stores frames for active function calls, placing the most recent unfinished call at the top until that function returns.
Very deep recursion can exhaust the call stack even when each individual function call is small.
Capacity
The capacity of an array is the number of available slots in its current backing storage, including slots not occupied by elements.
Size 6 and capacity 10 mean four slots are reserved for later additions without another resize.
Circular buffer
A circular buffer stores ordered data in a fixed block using indices that wrap around, allowing front removal without shifting other entries.
A queue front can advance from the final physical slot to slot 0 while preserving logical order.
Circular linked list
A circular linked list connects its final node back to its first, forming a cycle whose traversal must stop by a count or a return check.
A nonempty tail-only circular list finds its head through tail.next and rotates by advancing tail.
Compact array
A compact array stores same-type values directly in its slots, reducing the indirection and storage needed for separate object references.
Python's array module can store a sequence of C integers directly in a compact block.
Constant factor
A constant factor is a fixed multiplier hidden by an asymptotic bound that can affect measured speed without changing the growth order.
Cache misses can give a linked traversal a larger constant factor than an array scan.
Contiguous storage
Contiguous storage places equal-size array slots next to one another in one uninterrupted memory block, allowing direct address calculation.
An array can reach slot 20 without following links through the preceding 20 elements.

D

Data structure
A data structure is a concrete organization of data in memory together with the algorithms that perform operations on that data.
A dynamic array and a linked list are different data structures that can implement a sequence.
Deque
A deque is a double-ended queue that supports adding, inspecting, and removing at both ends, allowing either stack or queue access patterns.
A recent-action deque can append new actions and discard the oldest actions from its opposite end.
Dequeue
To dequeue is to remove and return the front element of a queue, reporting an error when the queue contains no elements.
A circular dequeue clears the current front slot, advances front, and decreases size.
Doubly linked list
A doubly linked list stores both previous and next references in each node, supporting movement in either direction and local node deletion.
A playlist cursor can move back one song without restarting a traversal from the head.
Dynamic array
A dynamic array stores a sequence in fixed-size backing storage that it replaces with a larger array when more capacity is needed.
Appending to a full dynamic array copies the current entries into new storage before adding the value.

F

FIFO
FIFO means first-in, first-out, the rule that the earliest addition still waiting is the next item removed from a collection.
A print queue follows FIFO when jobs are processed in arrival order without priority changes.
Fixed-step growth
Fixed-step growth adds the same number of slots at each resize, causing quadratic total copy work over a long run of appends.
Adding 5 slots per growth repeatedly copies arrays only slightly larger than the previous ones.
Front index
A front index identifies the first logical element in a circular array, providing the origin for translating logical positions into physical slots.
With front 5 and capacity 8, logical position 3 is stored in physical slot 0.

G

Geometric growth
Geometric growth multiplies capacity by a fixed factor greater than 1, making successive resize sizes form a geometric progression.
Doubling copies capacities 1, 2, 4, and 8 before the backing array first reaches capacity 16.
Growth factor
A growth factor is the fixed multiplier used to enlarge capacity; a larger factor leaves more spare space but usually requires fewer resizes.
A factor of 1.5 leaves less unused capacity than doubling while still supporting amortized fast appends.

H

Head
The head of a linked list is its first real node, providing the entry point for forward traversal and constant-time front changes.
After removing a nonempty list's first node, head advances to the removed node's successor.

I

Interface
An interface is the set of public operations through which code uses a collection while keeping its internal representation hidden.
A stack interface lets a client push and pop without reaching into the backing Python list.

K

Key-based lookup
A key-based lookup finds an item by an identifying value, not its position, so an unsorted linear collection may need a full search.
A customer ID does not reveal the array index of that customer unless another structure maps it.

L

LIFO
LIFO means last-in, first-out, the rule that the newest remaining addition is the next item removed from a collection.
Nested function calls follow LIFO because an inner call returns before its caller resumes.
Linear search
A linear search checks elements one at a time until it finds the requested value or reaches the end, taking linear time in the worst case.
An unsorted array may need a linear search even though reading any known index is constant time.
Locality
Locality is the tendency for an access pattern to reuse nearby memory, allowing successive operations to benefit from data already in cache.
Scanning consecutive array slots often has better locality than following scattered linked nodes.

M

Memory overhead
Memory overhead is storage used to support a representation beyond the elements themselves, such as spare array slots or node link fields.
Two links and separate-object storage contribute to each doubly linked node's memory overhead.

N

Node
A node is an object that stores an element together with one or more references connecting it to neighboring elements in a linked structure.
A singly linked node holds its element and a next reference, allowing the chain to continue.

O

Operation cost
An operation cost counts work for a fully specified action, including where it acts and any search needed to obtain the position.
A held-node edit is cheap, but an edit requested by index may first require a linear walk.

P

Packed sequence
A packed sequence uses consecutive array slots from index 0 through size minus 1, with no gaps among its stored elements.
Deleting from a packed sequence shifts the later entries left so indexing still follows logical position.
Palindrome
A palindrome is a sequence that reads the same forward and backward, which can be checked by repeatedly comparing its opposite ends.
The word "civic" passes opposite-end comparisons and leaves a single unpaired center letter.
Position
A position is a retained reference to a location in a linked sequence, allowing a local edit without finding that location again by index.
A doubly linked cursor position permits constant-time deletion of the current node.
Postfix expression
A postfix expression places each operator after its operands, allowing a stack to combine intermediate results without parentheses.
The postfix fragment 9 4 - computes 9 minus 4 because the first popped operand is the right one.
Predecessor
A predecessor is the node immediately before another node in a sequence; its next reference must change when that following node is removed.
A singly linked list may need to walk from head to find the predecessor of its final node.

Q

Queue
A queue adds elements at the back and removes them from the front, preserving the order in which waiting elements arrived.
A request queue serves the oldest waiting request before a request that arrived later.

R

Random access
Random access means reading or updating a chosen index directly, without traversing the elements that come before that position.
A dynamic array supports random access even when requested indices arrive in an unpredictable order.
Reference
A reference is a value that identifies an object in memory, allowing code to reach the object without storing that object inside the reference.
Two row references can point to the same inner list, so changing one row can affect both views.
Referential array
A referential array stores references in equal-size slots while the objects they identify can have different types and live elsewhere.
A Python list can hold an integer and a string because both slots store references to objects.
Representation invariant
A representation invariant is a condition on internal state that an implementation must preserve before and after every operation.
A head-and-tail list violates its invariant if an empty list still has a tail referring to a removed node.
Resize thrashing
Resize thrashing is repeated expensive growth and shrinking caused by operations that alternate across resize thresholds placed too close together.
Shrinking at half occupancy can undo the growth triggered by the immediately preceding append.
Resizing
Resizing replaces an array's backing storage with a differently sized block and copies the stored entries into that replacement.
A circular queue resize copies logical queue order so wraparound does not reorder waiting requests.
Rotation
A rotation moves items across a sequence's ends while preserving cyclic order; a positive Python deque rotation moves items right.
Rotating [A, B, C] right by one gives [C, A, B], making C the next front item.
Round-robin scheduling
Round-robin scheduling gives each waiting participant one turn in recurring order, returning unfinished work to the back and removing completed work.
A task that finishes its current time slice leaves the cycle, so later rounds skip it.
Row-major order
Row-major order stores all entries of the first row, then the second row, and so on, in one flat rectangular array layout.
In a table with 6 columns, reaching row 2 skips 12 slots before any column offset is added.

S

Sentinel
A sentinel is a boundary node that holds no sequence element and simplifies link changes by giving real endpoint nodes a neighbor.
Header and trailer sentinels are adjacent when a doubly linked list contains no real elements.
Sequence
A sequence is an ordered collection whose elements are identified by position and can be read, updated, inserted, or removed by position.
Inserting a new first element changes the positions of the existing elements in a sequence.
Shifting
Shifting moves an array suffix one slot left or right to close a deletion gap or create room for a new element at a position.
Right shifting begins at the back so a value is saved before its old slot is overwritten.
Singly linked list
A singly linked list is a sequence of nodes connected by next references, with the final node referring to None in a noncircular list.
A singly linked list can remove its head directly but must find a predecessor to remove its tail.
Size
The size of a collection is the number of elements it currently stores, excluding unused reserved slots or structural sentinel nodes.
A dynamic array with size 6 exposes nonnegative read indices 0 through 5, even if it has spare capacity.
Sliding window
A sliding window retains a moving portion of a sequence as new entries arrive and old entries expire, often using opposite deque ends.
A sensor window appends each new reading at the back and removes its oldest reading at the front.
Stack
A stack is a collection that adds and removes elements at one accessible end called the top, serving the most recently added element first.
An undo stack removes the newest action before it can reach an earlier action.
Static array
A static array reserves a fixed number of equal-size slots when created; its capacity cannot change without replacing its storage.
A preallocated array of 256 slots can accept another element only while some of those slots remain free.

T

Tail
The tail of a linked list is its final real node; keeping a tail reference supports direct insertion after the current last element.
A tail reference speeds enqueue but does not identify the predecessor needed for a singly linked tail removal.
Top
The top is a stack's currently accessible element; peeking returns it unchanged, while popping removes it and exposes the next item.
A list-backed stack keeps top at the final used index so push and pop avoid front shifts.
Traversal
A traversal visits a collection's elements in a chosen order, following next references from head to the end in a noncircular singly linked list.
A search traversal stops at a matching value or continues until the next reference becomes None.

W

Workload
A workload is the complete mix of operations used to assess a structure, including searches, edits, and reads across the program's task.
A linked list's cheap appends can be outweighed by repeated linear-time indexed reads in the workload.
Worst-case cost
A worst-case cost bounds the work of the most expensive operation or input of the stated size, including any resize or required traversal.
One full-array append has linear worst-case cost because it copies every existing entry.
Wraparound
Wraparound maps an index past either physical end of a circular array back into its slot range, using modulo arithmetic in Python.
An enqueue after the final slot wraps to slot 0 if that slot is available.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started