Hello I have been working on https://leetcode.com/problems/2-keys-keyboard/submissions/ and came upon this dynamic programming question.
You start with an 'A' on a blank page and you get a number n
when you are done you should have n
times 'A' on the page. The catch is you are allowed only 2 operations copy (and you can only copy the total amount of A's currently on the page) and paste --> find the minimum number of operations to get n
'A' on the page.
I wrote the following algorithm that solves the problem but I am having a tough time analyzing it's time complexity.
Here is the code:
def minSteps(self, n: int) -> int:
DP = [0] + [0] + [i for i in range(2, n+1)]
for d in range(2, n+1):
for i in range(d*2, n+1, d):
DP[i] = min(DP[i], DP[d] + i//d )
return DP[n]
So my intuition says this this algorithm is in between O(n^2)
and O(nlogn)
since in the second loop we are going "faster" than O(n)
however since the step size d
does not double between each iteration it is still O(n)
somewhat for the second loop...
I am not sure how to analyze that one, any help is welcome.
Let's look at the outer loop - it is performed O(N)
times.
Each inner loop is doing O(N / d)
operations, since the jumps of the index is in d
.
So the calculation is:
N / 1 + N / 2 + N / 3 + ... + 1
Notice that there are N
items in this sum.
We can take the N
out:
N * (1 / 1 + 1 / 2 + 1 / 3 + ... + 1 / N)
Which is approximately:
N * ln N
(The intuition is that by integrating the function 1 / N
you get ln
)
So the complexity over all is O(N log N)