Exercise 22 of 30 · intermediate · dynamic arrays · quadratic · hidden cost
Inserting at the front of an array list, n times
The code
result = []
for x in items:
result.insert(0, x) # list.Insert(0, x), add(0, x), v.insert(v.begin(), x)What does building the reversed list this way cost?
Count: element shifts.
Measured counts
Table
| n | count |
|---|---|
| 8 | 28 |
| 16 | 120 |
| 32 | 496 |
| 64 | 2,016 |
| 128 | 8,128 |
| 256 | 32,640 |
| 512 | 130,816 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n²)
- Extra space
- Θ(n)
- Exact count
- 0 + 1 + … + (n − 1) = n(n − 1)/2 shifts
- Inserting at index 0 of a list of size k shifts k elements.
- Sizes go 0, 1, …, n − 1: n(n − 1)/2 shifts.
- Append then reverse (Θ(n)), or use a deque with appendleft / addFirst.
Common mistake: Treating list insert as O(1) because append is. Only the end is cheap.
Check: measured count ÷ (n²) settles near 0.499 for large n.