Search code examples
algorithmdynamicappendamortized-analysis

Amortized Runtime When Increasing Dynamic Array by Varying Sizes


I have a dynamic array that I am constantly appending items onto. An append is complexity O(1). When the array becomes full, I would like to grow the array and copy it over, which is complexity O(n).

Now, suppose I am growing the array at different rates when it becomes full. These rates are:

i) Some constant C

ii) n/2

iii) n^2

What is the amortized runtime in each of these scenarios?

I believe that I was able to solve case i. The amortized runtime will be the total cost of operations divided by the total number of operations. In this case, the total cost is C * O(1) + 1 * O(n), and the total number of operations is C. Thus, the amortized runtime is O(n).

However, I'm a little lost when analyzing the two remaining cases. It seems to me that the total number of operations will be n/2 + 1 and n^2 + 1, respectively, but I don't quite know how to calculate the total cost of operations.

Can anyone lead me on the right path?


Solution

  • You can use a similar analysis to the first case.

    ii.
    (n/2 * O(1) + O(n)) / (n/2) = O(1) + O(n)/n = O(1)
    iii.
    (n^2 * O(1) + O(n)) / (n^2) = O(1) + O(n)/n^2 = O(1)
    

    This answer gives a more detailed explanation as to why a dynamic array that resizes in proportion to n (assuming it's resizing to n power of 1 or greater) has a constant amortized cost.