Time and Space Complexity
Solution
The amount of work an algorithm does as a function of the input size. We count primitive operations (steps). In the model of computation we use, each primitive step takes constant time, so the running time is proportional to the step count.
Solution
Time. By convention a complexity claim with no resource named is about time. When memory is meant, the claim says space complexity.
Solution
Space complexity is the total memory an algorithm needs, as a function of the input size. Input space is the memory the input itself takes. Auxiliary space is the extra memory the algorithm allocates while it runs. Space complexity input space auxiliary space.
Solution
| Method | Time | Space complexity | Input space | Auxiliary space |
|---|---|---|---|---|
doubledCopy |
||||
doubledInPlace |
Both make one pass over elements. doubledCopy allocates a second array of length . doubledInPlace allocates only the loop index.
Solution
When algorithms work on the same input, the input space is the same. Including it in the total can hide differences in auxiliary space: the two doubling methods above both have total space, even though one uses auxiliary space and the other uses . Comparing auxiliary space makes that difference visible. Total space can still distinguish algorithms when their extra memory grows faster than the input space.
Solution
The input includes the object add runs on, not just its parameter. add reads and writes arr and size, so the backing array counts as input space. For an array built by additions from a fixed initial capacity, the input space is , as shown below. (To be more careful, we should count the input space as : removing elements decreases but does not shrink the backing array. In that case, the best-case total space is also .)
add |
Input space | Auxiliary space | Space complexity |
|---|---|---|---|
| Best case | |||
| Worst case |
In the best case arr has room and add allocates nothing. In the worst case arr is full and grow allocates bigger, with slots.