Sub topic 15
Common pitfalls
This chapter assumes you know how a dynamic array tracks size and capacity, and that it resizes by allocating a new block and copying. It covers the mistakes that most often appear in code built on that idea.
Confusing size with capacity
Size is the number of elements stored. Capacity is the number of slots allocated. Only indexes below size are valid, even though more slots exist.
In the DynamicArray from earlier, __getitem__ checks against _size, not _capacity. If it checked capacity, a read at an unused slot would return None instead of raising an error.
Off-by-one errors
Valid indexes run from 0 to size - 1. The two common mistakes are looping to size and reading array[size].
insert is the exception. It accepts index == size, because inserting there is the same as appending. That is why its check is 0 <= index <= self._size.
Shifting cost hidden in a loop
One insert(0, x) shifts every element, so it costs O(n). Calling it inside a loop makes the whole loop O(n²).
items = []
for value in range(5):
items.insert(0, value)
print(items)This prints [4, 3, 2, 1, 0]. For large inputs, append in the loop and reverse once at the end. That costs O(n) in total.
Modifying while iterating
Removing or inserting elements while looping over the same array shifts the remaining elements under the loop. The loop then skips items.
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
print(nums)This prints [1, 2, 3], not [1, 3]. After the first removal, the second 2 moves into the slot the loop has already passed. Build a new list instead: nums = [n for n in nums if n != 2].
Holding references across a resize
A resize allocates a new block and discards the old one. In C++, a pointer, reference, or iterator into a vector becomes invalid after any operation that reallocates. Using it is undefined behavior. Java and Python avoid this because they hold object references, not raw addresses. Their iterators still raise errors if the collection changes during iteration.
Forgetting to clear the freed slot
In pop, the implementation sets the vacated slot to None. Without that, the array keeps a reference to the removed object, so it cannot be garbage collected. This is a memory leak in languages with garbage collection.
Shrinking too eagerly
If an array halves its capacity as soon as it is half full, a sequence of alternating appends and pops at that boundary triggers a resize every time. Each resize costs O(n), so the amortized guarantee is lost. A common fix is to shrink only when the array is a quarter full.
Summary of pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Using capacity as bound | Reads return `None` or garbage | Check against size |
| `insert(0, x)` in a loop | O(n²) running time | Append, then reverse |
| Mutating during iteration | Skipped elements | Build a new list |
| Stale reference after resize | Undefined behavior in C++ | Use indexes or `reserve` |
| Eager shrinking | Repeated O(n) resizes | Shrink at one quarter full |
Exercise
A loop runs for x in data: if bad(x): data.remove(x) on a Python list and sometimes skips elements. Why does it skip, and what is a safer approach?
Show answer
Removing an element shifts later elements one slot left, but the loop's internal index still advances, so the element that moved into the removed slot is never examined. Build a new list instead, for example data = [x for x in data if not bad(x)].