Implement push with doubling
Standard · Write code · about 10 min
data is the backing block of a dynamic array: its length is the capacity, the first size cells hold values and the rest hold 0.
Append x and return the backing block afterwards. If the block is full, first make a new block of twice the length (length 1 when it was empty), copy the size values into it with a loop, and fill the remaining cells with 0. Do not use built-in growth such as push, append or concat.
Example 1
Input:
[[1,2,0,0],2,3]
Output:
[1,2,3,0]
There is room: write 3 at index 2.
Example 2
Input:
[[1,2],2,3]
Output:
[1,2,3,0]
Full: copy into a block of 4, then write 3.
Constraints
- 0 ≤ size ≤ data.length ≤ 10,000
- Cells from index size on hold 0.
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
- Why 2× and not +1 Standard
- Implement a dynamic array with pop and shrink Challenge