Check if Array Is Sorted and Rotated (LeetCode 1752): Solution and Explanation

Easy
Array

Return true if nums could be a non-decreasing array rotated by some number of positions (zero included), and false otherwise. Duplicates are allowed.

Intuition

Call a position a drop when a value is larger than the value right after it. A sorted array has no drops at all.

Rotation cuts the sorted array once and puts the back piece in front. The only new neighbour pair is where the old last element now meets the old first element, so a rotated sorted array has at most one drop inside it.

Counting drops inside the array is not quite enough, though. [2,1,3,4] has one drop, but it is not a rotation. The fix is to close the array into a ring and also compare the last element with the first. On the ring, any sorted array has exactly one drop (the wrap from largest back to smallest) unless all values are equal, and rotating does not change the ring at all. So the test becomes: at most one drop around the whole ring.

Approach: Count drops around the ring

  1. Set drops = 0.
  2. For every index i, compare nums[i] with nums[(i + 1) % n]. The modulo makes the last element compare with the first.
  3. If nums[i] is larger, increment drops. If drops reaches 2, return false right away.
  4. If the loop finishes, there was at most one drop, so return true.

Step-by-step example

nums = [3,4,5,1,2]
  1. Edge 0 -> 1: 3 <= 4, no drop.
  2. Edge 1 -> 2: 4 <= 5, no drop.
  3. Edge 2 -> 3: 5 > 1, the first drop. If it is the only one, the sorted order starts at index 3.
  4. Edge 3 -> 4: 1 <= 2, and the wrap edge 4 -> 0: 2 <= 3. No more drops.
  5. One drop in total, so return true. Reading from index 3 around the ring gives 1, 2, 3, 4, 5.

Code: Python, Java, C++

1class Solution:
2    def check(self, nums: List[int]) -> bool:
3        n = len(nums)
4        drops = 0
5        for i in range(n):
6            if nums[i] > nums[(i + 1) % n]:
7                drops += 1
8                if drops > 1:
9                    return False
10        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each of the n ring edges is compared once.

Space

O(1)

Only the drop counter and the loop index are stored.

Other approaches

Try every rotation (time O(n^2), space O(1))

For each shift x, build or scan the rotated array and check whether it is sorted. It follows the definition literally but repeats the same comparisons n times.

Find the cut, then verify (time O(n), space O(1))

Find the first index where nums[i] > nums[i + 1]. Check that both pieces are sorted and that the last element is at most the first. It is correct but has more cases to get right than counting drops on the ring.

Common mistakes

  • Forgetting the wrap-around comparison. Without comparing the last element to the first, [2,1,3,4] has one drop and would wrongly return true.
  • Using >= instead of >. Equal neighbours are allowed because the order is non-decreasing, so [1,1,1] must return true.
  • Treating an already sorted array as invalid. Rotation by zero positions counts, so [1,2,3] is true.

Frequently asked questions

Why does a sorted array have one drop on the ring?

Going around the ring you climb from the smallest value to the largest, then the wrap edge goes from the largest back to the smallest. That wrap is the single drop, unless every value is equal, in which case there are none.

How do duplicates affect the check?

Only strict decreases count as drops, so runs of equal values never add to the count. [6,7,7,1,2,2,5] has a single drop, from 7 to 1, and returns true.

Where does the original sorted array start?

Right after the single drop. If there is no drop at all, every value is equal or the array is already sorted, and it can start at index 0.

Is this related to searching in a rotated sorted array?

Yes. Search in Rotated Sorted Array and Find Minimum in Rotated Sorted Array both rely on the same fact: a rotated sorted array is two sorted runs with one drop between them, which binary search can locate.