Implement a dynamic array with pop and shrink
Challenge · Write code · about 20 min
Build a dynamic array on a plain backing block and run a list of operations. It starts empty with capacity 1.
"push x"appends the integer x. If the block is full, first copy the values into a block of twice the capacity."pop"removes the last value. Afterwards, if the capacity is above 1 and size ≤ capacity / 4, copy the values into a block of half the capacity.
Return the capacity after each operation.
Example 1
Input:
[["push 1","push 2","push 3","pop","pop","pop"]]
Output:
[1,2,4,4,2,1]
The second pop leaves size 1 = 4 / 4, so the block halves to 2.
Example 2
Input:
[["push 5","pop","push 6"]]
Output:
[1,1,1]
Capacity never drops below 1.
Constraints
- 0 ≤ ops.length ≤ 10,000
- Every pop happens on a non-empty array.
- -10,000 ≤ x ≤ 10,000
Learn the idea first: Dynamic arrays: capacity, growth, amortized append, a visual lesson.
More Dynamic arrays: capacity, growth, amortized append problems
- Capacity after k appends Warm-up
- Count the copies of n appends Warm-up
- Implement push with doubling Standard
- Why 2× and not +1 Standard