#1752

Check if Array Is Sorted and Rotated

pupil · 405 · lc easy +24 · verified · 55.8% accepted · 4,882 likes · top 49%

Description

Given an array nums, return true if it could be obtained by taking a non-decreasing sorted array and rotating it by any number of positions (including zero). A rotation by x gives B[i] == A[(i+x) % A.length].

Example 1:

Input: nums = [3,4,5,1,2]
Output: true
Explanation: [1,2,3,4,5] is the original sorted array.
You can rotate the array by x = 2 positions to begin on the element of value 3: [3,4,5,1,2].

Example 2:

Input: nums = [2,1,3,4]
Output: false
Explanation: There is no sorted array once rotated that can make nums.

Example 3:

Input: nums = [1,2,3]
Output: true
Explanation: [1,2,3] is the original sorted array.
You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.

Code

1
2
3