May 23Easy
Check if array is sorted and rotated
- Array
Problem
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.
There may be duplicates in the original array.
Note: An array A rotated by x positions results in an array B of the same length such that B[i] == A[(i+x) % A.length] for every valid index i.
Solution
class Solution:
def check(self, nums: List[int]) -> bool:
rotated = False
for i in range(1, len(nums)):
if nums[i] < nums[i-1]:
if rotated:
return False
rotated = True
return not rotated or nums[0] >= nums[-1]