Solutions week 2 - Complexity
1
logn, 4n, nlogn, 5n2+n, 3n3, n4
2
T(n)=2n×1e−6T(n)=5e9×365×24×60×60 so 2n×1e−6=5e9×365×24×60×602n=5e9×365×24×60×60×1e62n=1.5768e23log2(2n)=log21.5768e23n=77.06134586390338
Thus, max 77 steps.
3
n=50
10×2n=11258999068426240≈357 years
-> unreasonable10000log2n=56438.561... microsec<1 seconds
-> reasonable, no problem100000n=5000000=5 seconds
-> reasonable10n!=30414093201713...≈9.6e51 years
-> unreasonable
4
O(34x+x2)=O(34x)+O(x2)=O(x)+O(x2)=O(x2)
O(1x+2x+3x+4x+5x+6x+7x)=O(28x)=O(x)
O(104000x+0.005x2+103x3)=O(104000x)+O(0.005x2)+O(103x3)=O(x)+O(x2)=O(x2)
103x3 approaches 0 as x approaches infinity
O(10log2x+2log10x)=O(10log2x)+O(2log10x)=O(logx)+O(logx)=O(logx)
The base of the logarithm is irrelevant in big-O notation since using the logarithm law we have logan=logbnlogba for any constants a and b, and since logba is constant we have O(log10n)=O(logn).
O(2x+10x)=O(2x)+O(10x)=O(10x)
10x and 2x are different as they do not differ by a constant, since 10x2x=5x and so O(10x)≠O(2x).
O((x−2)(x−1)x)=O(x−2)×O(x−1)×O(x)=O(x)×O(x)×O(x)=O(x×x×x)=O(x3)
5
Given a size of n, it takes O(n) time in the worst case as an increase (resize) in size of the internal array might be needed.
Assuming the ArrayList
is initially empty, adding O(n) elements takes O(n) time. See for example lecture slides for explanation.
6
See the ArrayList
javadoc documentation. It shifts n - 1
elements to the left in the worst case (that is if we remove the first element), so O(n).
If we are allowed to change the order of the elements, we can do a delete in constant time. For example, by swapping the to be removed element with the last element and decreasing the size of the list by one.
7
See for example Duplicates.java
and NoDups.hs
.