Dynamic Array

This chapter discusses the time complexity of insert operations on a dynamic array.

What is it?

A dynamic array resizes itself automatically when it runs out of capacity and new elements need to be added to it. In Java, the ArrayList class is one such example. The official Java documentation states:

/**
* As elements are added to an ArrayList, its capacity grows automatically.
* The details of the growth policy are not specified beyond the fact that 
* adding an element has constant amortized time cost.
*
*/

Note that a dynamic array only resizes itself to grow bigger, but not smaller. The claim is that the amortized cost of inserting n elements in a dynamic array is O(1) or constant time.

Implementation

We know that an array is a contiguous block of memory and can't be resized. Internally, a dynamic array implementation simply discards the previous allocation of memory and reallocates a bigger chunk. When the existing members are copied over to the new array and now new ones can also be added because of additional capacity.

One common strategy is to double the array size whenever it reaches full capacity. Below, we'll work out the complexity for this strategy.

First Element

We'll trace how an array expands, starting with a size of 1 as new elements get added. The initial state of the array is shown below with one element.

%0 node_3 7

Second Element Added

Now we add another element. Since the capacity is 1, we need to double it to 2 elements. We copy the previous element and insert the new one.

Cost = 1 copy + 1 new insert

%0 node_1 7 node_2 8

Third Element Added

Since we don't have any more capacity, we'll need to double our array size again. Note that, at this point, we'll need to copy the previous two elements and add the new element.

Cost = 2 copies + 1 new insert

%0 node_1 7 node_2 8 node_3 2 node_1538025355128

Fourth Element Added

When we want to add the fourth element, there's one empty slot in our array where we can insert it without having to resize the array.

Cost = 1 new insert

%0 node_1 7 node_2 8 node_3 2 node_1538025355128 5

Fifth Element Added

When we want to add the fifth element, there's no space in the array, so we need to double the array size from four to eight. We'll need to copy the four elements from the old array to the new array and insert the fifth element.

Cost: 4 copies + 1 new insert

%0 node_1 7 node_2 8 node_3 2 node_1538025355128 5 node_1538027823183 0 node_1538027796875 node_1538027783254 node_1538027820789

Sixth, Seventh & Eight Element Added

We have space for 3 more elements, so we ...

Access this course and 1400+ top-rated courses and projects.