Sub topic 2
Arrays and dynamic arrays
This chapter assumes you can write loops and functions, know what a reference (pointer) is, and have met O(1) and O(n) notation. It covers the array side of the comparison: what a fixed array is, how a dynamic array builds on it, and which operations each makes cheap or expensive.
What an array is
An array is a block of memory holding elements of the same size, one after another with no gaps. The previous chapter showed the layout. Here we use its main consequence: the address of any element can be computed.
If the block starts at address base and each element takes size bytes, element i lives at:
address(i) = base + i * sizeThis is one multiplication and one addition. The cost does not depend on i or on the array's length, so reading or writing by index is O(1).
A fixed array has a capacity chosen when it is created. It cannot grow in place, because the memory after it may belong to something else.
From fixed arrays to dynamic arrays
A dynamic array wraps a fixed array and tracks two numbers:
- capacity: how many slots the underlying block has.
- size: how many slots hold real elements.
Appending writes into slot size and increments size. When size equals capacity, the structure allocates a larger block, copies every element over, and discards the old block. Python's list, Java's ArrayList and C++'s std::vector all work this way.
A working implementation
This class follows the diagram. It doubles the capacity whenever the buffer is full.
class DynamicArray:
def __init__(self):
self._capacity = 1
self._size = 0
self._items = [None] * self._capacity
def append(self, value):
if self._size == self._capacity:
self._resize(2 * self._capacity)
self._items[self._size] = value
self._size += 1
def _resize(self, new_capacity):
new_items = [None] * new_capacity
for i in range(self._size):
new_items[i] = self._items[i]
self._items = new_items
self._capacity = new_capacity
def __getitem__(self, index):
if not 0 <= index < self._size:
raise IndexError(index)
return self._items[index]
def __len__(self):
return self._sizeNote the bounds check in __getitem__. Without it, an index between size and capacity would return a leftover None instead of an error.
Costs of the main operations
| Operation | Cost | Reason |
|---|---|---|
| Read or write by index | O(1) | Address arithmetic |
| Append | O(1) amortized | Occasional O(n) resize, covered in a later chapter |
| Insert or delete at index `i` | O(n) | Elements after `i` must shift |
| Insert or delete at the end | O(1) amortized for insert, O(1) for delete | Nothing shifts |
| Search for a value (unsorted) | O(n) | Each slot may need checking |
Insertion in the middle is the weak point. Inserting at index 1 of [1, 3] moves 3 one slot right:
items = [1, 3]
items.insert(1, 2) # later elements shift one slot right
print(items) # [1, 2, 3]Inserting at the front of a list with a million elements moves a million elements. Appending to the same list usually moves none.
Common errors
- Assuming every append is cheap. Most appends are O(1), but the append that triggers a resize copies everything. This matters in code with strict per-operation latency limits.
- Inserting or removing at the front in a loop. Each call is O(n), so the loop is O(n²). Python's
list.pop(0)is a typical case. - Holding on to positions across changes. An index means "the i-th element now". After an insert or delete before it, the same index refers to a different element.
- Confusing capacity with size. Memory use follows capacity, while
lenreports size. A list that grew large and was then emptied may keep its large block.
What arrays give you
Arrays give fast indexed access and compact storage, because elements sit side by side with no per-element bookkeeping. Dynamic arrays add cheap appends on top. The price is slow insertion and deletion away from the end, and occasional full copies when the buffer grows.
Exercise
A dynamic array holds 8 elements with a capacity of 8. You call append once. What happens, and what is the cost of that single call?
Show answer
The size equals the capacity, so the structure allocates a larger block (for example capacity 16), copies all 8 elements into it, writes the new value, and sets size to 9. That single call costs O(n), because of the copy. Appends that do not hit a full buffer cost O(1).
Exercise
You need to repeatedly remove the first element of a Python list while processing 100,000 items. Why is items.pop(0) in a loop a problem, and what is the total cost?
Show answer
Each pop(0) shifts all remaining elements one slot left, which is O(n). Repeating it n times gives O(n²) total. Popping from the end is O(1), and a structure that removes from the front cheaply, such as a linked list or a deque, avoids the repeated shifting.