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
.
An array is said to be rotated if one could rotate some pivot
index and get the original array in sorted order.
For example, array [3, 4, 5, 1, 2]
is considered rotated at pivot index 2 because it becomes sorted array [1, 2, 3, 4, 5]
after rotating left twice.
nums
array?
def check(nums):
count_drops = 0
n = len(nums)
# Count the number of drops in the array
for i in range(n):
if nums[i] > nums[(i + 1) % n]:
count_drops += 1
# The array can be sorted and rotated if and only if there is at most one drop
return count_drops <= 1
# Example usage
print(check([3, 4, 5, 1, 2])) # Should return True
print(check([2, 1, 3, 4])) # Should return False
print(check([1, 2, 3])) # Should return True
The time complexity of this solution is O(n)
, where n
is the number of elements in the array. We traverse the array once to count the drops, making the solution efficient.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?