I was solving this problem on Hacker rank. My algorithm to solve the problem is:
- Get an array of all the player scores. Iterate through all player scores and create a new array. Let there be n players in all.
which doesn't contain any repeated player scores. Let us call the new array, playerScores.- Let total levels to be played by Alice is m.
- Let Alice's score after first round be S.
- Let Alice's initial rank R be 0.
- Start iterating playerScores array from the rear end until you get a player score whose score is less than S.
- Set R to rank of the player found in step 5.
- Reduce m by 1.
- Print R.
- Now start processing Alice's score in all subsequent m-1 levels inside a loop
- Set S to Alice's next level score.
- Start iterating playerScores array from the player whose rank is R-1 towards the front end.
- Continue iteration untill you get a player whose score is less than S.
- Set R to rank of the player found in above step.
- Reduce m by 1.
- Print R.
- Go to step 9.1 if there are more levels left to be played (i. e m>0).
Now when I started calculating the Big O time complexity of the above algorithm, I realized that it should be O(n) as below:
Adding above two factors the time complexity comes out to be O(n + n) = O(2n) = O(n). While my friend claims it to be O(n + m) though he isn't able to explain it enough. Can anyone help me understand the same if my formulation of O(n+n) complexity is anyway flawed?
O(n+m)
is different from O(n+n)
or O(n)
when you don't know what would be the relation between m
and n
. It may be that sometimes n
might be larger than m
and other times m
might be larger but there is no definite way to tell. If however, you always know that n>=m
no matter what, you can say that O(n+m)
will actually be O(n)
. In this case, same rule apply.