Insert and delete: the cost of shifting
🌍 In real life. Eight friends sit in a row of cinema seats with no gaps. A ninth friend arrives and wants the first seat: everyone has to get up and move one seat along, eight people moving for one new arrival. If they sit at the end instead, nobody moves. And when the person in seat 2 leaves, everyone after them shuffles left to close the gap.
An array has the same rule: its items must stay side by side, in order, with no gaps.
The idea in one sentence: changing an array anywhere but the end means shifting every item after that place by one, so the cost depends on where you change it.
Its words:
- shift: moving every item after a spot one place right (to make a gap) or left (to close one)
- in place: changing the list itself instead of building a new one
- the end: the one spot in a list where adding or removing needs no shifting at all
How it works, step by step:
items.insert(i, x): the items from position i to the end each move one place right (starting from the last, so nothing is overwritten), then x goes into the gap at iitems.pop(i): the item at i is taken out, then every item after it moves one place left to close the gapitems.append(x)anditems.pop()work at the end, so nothing moves
Watch the move counter: it jumps for changes at the front and in the middle, and stays still at the end.
Why it must shift. Item i is found at start + i × size (lesson 1). If a gap were left, or two items shared a place, that sum would point at the wrong item. Shifting is the price of O(1) reading.
What it costs, worked out. In a list of n items, insert(i, x) moves the n − i items from position i on, and pop(i) moves the n − i − 1 items after it. At the front that is about n moves: O(n). At the end it is 0: O(1). So:
items[i],items[i] = x,len(items): O(1)append(x),pop(): O(1) (append amortised, lesson 2)insert(i, x),pop(i): O(n − i), so O(n) near the frontx in items,items.index(x),items.remove(x): O(n), they walk the list
If your program keeps adding and removing at the front, a list is the wrong tool: collections.deque does both ends in O(1) (Chapter 40 builds one).
def insert_at(items, i, x):
items.append(None) # one more place at the end
moves = 0
for k in range(len(items) - 1, i, -1):
items[k] = items[k - 1] # move one place right, from the end
moves += 1
items[i] = x
return moves
seats = ["Rafi", "Mitu", "Tanim"]
print(insert_at(seats, 0, "Nila"), seats)
print(insert_at(seats, 4, "Joy"), seats) # at the end: no movesMistakes and edge cases. Removing items from a list while looping over it skips items: after a removal everything shifts left, and the loop's next step jumps over the item that slid into the gap. Build a new list instead ([x for x in items if x != 0]), or loop over a copy. And items.remove(x) raises ValueError when x isn't there.
Quiz
For
items.insert(2, x), how many items have to move? What does this print?items = [10, 20, 30, 40, 50, 60] i = 2 print(len(items) - i)Which of these is O(n) on a list of n items?
- items.pop(0)
- items.pop()
- items[0]
What does this print?
items = [3, 1, 4] items.insert(1, 9) items.pop(0) print(items)This should remove every 0, but [0, 0, 5] gives [0, 5]. Which line causes it?
def drop_zeros(items): for x in items: if x == 0: items.remove(x) return itemsA program adds every new job at the front of a list of 100,000 jobs. What is the better choice?
- Use collections.deque, which adds at either end in O(1)
- Keep insert(0, job): it is O(1)
- Sort the list after every insert
Coding tasks
Write
insert_at(items, i, x)withoutinsert: add one place at the end, move each item from the end down to positionione place right, putxati, and give back how many items moved.Write
remove_at(items, i)withoutpop(i),delorremove: keep the item ati, move every item after it one place left, drop the now-spare last place withitems.pop(), and give back(removed item, moves).