In other words, when the smallest element is at the 0th index.

def count_rotations_linear(nums):
position = 1
while position < len(nums):
if position > 0 and nums[position] < nums[position - 1]:
return position
position += 1
return -1

If you had a list like this: nums = [4, 5, 1, 2, 3]
Then the possible number of rotations are:

2

7

12

…

2 + 5*n for n >= 0

But the task asks for the minimal number of rotations. So, for the case above, it’s 2.
Now, you can rotate list only len(nums) - 1 times before it becomes again sorted. Rotating one more time would cause it to go back to it’s initial state (and it would seem as if it was rotated 0 times). So your possible answers range from 0 to len(nums) - 1.

In your case above the condition would never be true, so you would exit the loop (basically when position == len(nums)) and return -1. Why -1, if it’s not a possible number of rotations?

How do I check the condition where there is only 1 element in the list. I have got the following code now:

def count_rotations_linear(nums):
position = 0 # What is the intial value of position?
while position < len(nums): # When should the loop be terminated?
# Success criteria: check whether the number at the current position is smaller than the one before it
if position >= 0 and nums[position] < nums[position - 1]: # How to perform the check?
return position
# Move to the next position
position += 1
return -1

If there’s only one element in the list, then you would leave the loop immediately with position = 1 (it would not execute even a single time).
And you would return -1

Why -1, if it’s not a possible number of rotations?

-1 because I had put the output as -1 for the case where the list is empty. If I change the output to 0 for that case too, then everything runs fine.
In the above case where list has only one element I leave with position as 0. Means the list was rotated 0 times, cause its just 1 element.
I have changed the condition given previously as position > 0
in the template to position >= 0
thus everything works.
What would the condition be if I don’t do that?

If the list empty, then there’s simply no possible number of rotations. You could say though that it has been rotated 0 times (and I think most people did/though/implemented it this way).

The condition to check if position is > 0 was kinda “dead code” for me (since with your position = 1 it would be never true), but not hampering the solution in any way. You can remove it and it will still work.

You basically have to check only if current element is greater than the next element. If it is, then you’ve found the number of rotations. Just make sure to not reach for nums[-1]. It will work, but it’s gonna pick the last element from nums list.