Sub topic 6
Inserting and Deleting by Shifting Elements
This chapter assumes you know basic Big-O notation and that an array stores its elements in one contiguous block of memory, so index i lives at a fixed offset from the start. That layout makes reads fast. It also makes changes in the middle costly, because there are no gaps to use.
Why the middle is expensive
Elements in an array must stay next to each other, with no holes. To insert a value at index k, every element from k onward has to move one slot to the right first. To delete the value at index k, every element after it has to move one slot to the left to close the gap.
The number of elements that move depends on where you insert or delete.
| Operation | Elements moved | Cost |
|---|---|---|
| Insert or delete at the end | 0 | O(1) |
| Insert or delete in the middle | about n/2 | O(n) |
| Insert or delete at the front | n | O(n) |
Big-O keeps only the worst case, so any operation that can touch the front is O(n).
Insert in code
The shift loop must run from the right end toward the insertion point. If it ran left to right, each write would overwrite the next element before it had been copied.
def insert(self, index, value):
if not 0 <= index <= self._size:
raise IndexError("index out of range")
if self._size == self._capacity:
self._resize(2 * self._capacity)
for i in range(self._size, index, -1):
self._data[i] = self._data[i - 1]
self._data[index] = value
self._size += 1The bounds check allows index == self._size, which means "insert at the end." That case runs the loop zero times. The resize check matters here too. Insertion needs one free slot, and a full array has none. Resizing is covered in a later chapter.
Delete in code
Removing the last element needs no shifting. You decrease the size and clear the old slot:
def pop(self):
if self._size == 0:
raise IndexError("pop from empty array")
self._size -= 1
value = self._data[self._size]
self._data[self._size] = None
return valueDeleting from the middle uses the same idea in the other direction. Copy each later element one slot left, from the deletion point upward, then shrink the size.
The same behavior in Python's list
Python's built-in list is a dynamic array, so it has the same costs:
items = [10, 20, 30]
items.append(40)
items.insert(0, 5)
last = items.pop()
first = items.pop(0)
print(items, last, first)This prints [10, 20, 30] 40 5. The calls append(40) and pop() work at the end and are cheap. The calls insert(0, 5) and pop(0) shift every other element, so each costs O(n).
Common mistakes
- Shifting in the wrong direction when inserting, which overwrites data.
- Forgetting to update
_sizeafter a shift. - Rejecting
index == sizeon insert, which blocks valid appends. - Leaving a stale reference in the vacated slot. In a language with garbage collection, that keeps the old object alive.
Exercise
A dynamic array holds 1,000 elements and has spare capacity. About how many elements move when you insert a new value at index 250, and what is the Big-O cost of the operation?
Show answer
The elements at indexes 250 through 999 move one slot right, which is 750 elements. The cost is O(n), since the number of moves grows in proportion to the array length.
Exercise
Why must the insert loop in the code above run from the end of the array toward the insertion index, instead of from the insertion index toward the end?
Show answer
Copying left to right would write data[k+1] = data[k] and then data[k+2] = data[k+1], which now holds the old data[k]. Every later slot would end up with the same value, and the original elements would be lost. Going right to left copies each element before its slot is overwritten.