Problem Description
Given an array of numbers, determine if the array was originally sorted in non-decreasing order and then rotated some number of positions (including zero rotations). The array may contain duplicates.
Key Insights
- A sorted, then rotated array will have at most one position where an element is greater than its immediate next element (taking wrap-around into account).
- Count the number of "drop" points where nums[i] > nums[(i+1) % n]; if this count is more than one, the array cannot be a rotated sorted array.
- An array with no drop points or exactly one drop point satisfies the condition.
Space and Time Complexity
Time Complexity: O(n) - we traverse the array once. Space Complexity: O(1) - constant extra space is used.
Solution
We iterate through all elements of the array and compare each element with the next element (using modulo to handle the last element comparing with the first). A counter tracks the number of times an element is greater than its next. If this counter exceeds one, then the array is not sorted and rotated. Otherwise, it is.