Sub topic 1
Cost model: counting operations and memory
Prerequisites
This chapter assumes you can write loops and functions in Python, C, or Java, that you understand pointers or object references, and that you know basic Big-O notation. Examples use Python.
Cost model: counting operations and memory
Time cost counts the steps an operation takes as the input size n grows. Space cost counts the extra memory it needs beyond the input. Report both as Big-O terms such as O(1) or O(n).
Arrays: contiguous memory and index arithmetic
An array stores its elements in one contiguous block. If the block starts at address B and each element takes s bytes, element i sits at address B + i × s. The computer jumps straight to that address, so access by index takes O(1) time.
Array operations: access, search, insert, delete
| Operation | Time | Reason |
|---|---|---|
| Access by index | O(1) | Direct address calculation |
| Search (unsorted) | O(n) | May scan every element |
| Insert or delete at the end | O(1) | No elements move |
| Insert or delete at the front or middle | O(n) | Later elements must shift |
Singly linked lists: nodes, traversal, insertion, deletion
A singly linked list stores each value in a node that holds a pointer to the next node. Reaching position k requires walking from the head, so access takes O(n). Once you hold a reference to the right node, insertion or deletion changes only a few pointers.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = nextDoubly and circular linked lists
A doubly linked list node has both prev and next pointers. Deleting a node you already hold takes O(1), because you can reach its predecessor directly. A circular list makes the last node point back to the head, so traversal never ends unless the loop stops by a count or by returning to the start.
Reversal, middle node, and cycle detection
Reversal rewires each node's next pointer to the previous node in one pass:
def reverse(head):
prev = None
while head is not None:
nxt = head.next
head.next = prev
prev = head
head = nxt
return prevTo find the middle node, move a slow pointer one step and a fast pointer two steps per iteration. When the fast pointer reaches the end, the slow pointer sits at the middle. The same two-pointer idea detects a cycle: if the fast pointer ever meets the slow pointer, the list loops.
Exercise
Reversing a list of n nodes changes how many next pointers, and what is the time and extra space cost?
Show answer
Each node's next pointer is changed once, so n assignments. The time is O(n) and the extra space is O(1), since only three references are used.