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

050k1.0e+2k200400ncount
Measured
Table
ncount
828
16120
32496
642,016
1288,128
25632,640
512130,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
  1. Inserting at index 0 of a list of size k shifts k elements.
  2. Sizes go 0, 1, …, n − 1: n(n − 1)/2 shifts.
  3. 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.