Search code examples
algorithmtime-complexitybig-oasymptotic-complexity

When is an algorithm O(n + m) time?


I was solving this problem on Hacker rank. My algorithm to solve the problem is:

  1. 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.
  2. Let total levels to be played by Alice is m.
  3. Let Alice's score after first round be S.
  4. Let Alice's initial rank R be 0.
  5. Start iterating playerScores array from the rear end until you get a player score whose score is less than S.
  6. Set R to rank of the player found in step 5.
  7. Reduce m by 1.
  8. Print R.
  9. Now start processing Alice's score in all subsequent m-1 levels inside a loop
    1. Set S to Alice's next level score.
    2. Start iterating playerScores array from the player whose rank is R-1 towards the front end.
    3. Continue iteration untill you get a player whose score is less than S.
    4. Set R to rank of the player found in above step.
    5. Reduce m by 1.
    6. Print R.
    7. 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:

  1. One scan is required to get non-duplicate scores. This contributes to factor n. It is possible that all scores are unique.
  2. Another scan from tail to front is required to decide Alice's rank after each level. This contributes to factor n again. In worst case number of levels (m) can be equal to number of players (n).

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?


Solution

  • 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.