Suppose we have an array called nums, we have to check whether the array was originally sorted in non-decreasing order, and then rotated some number of positions (may be zero) or not. Duplicates may also present in the array.
So, if the input is like nums = [12,15,2,5,6,9], then the output will be True, because it is rotated to the right for two places
To solve this, we will follow these steps −
j := 0
while j < size of nums - 1 and nums[j] <= nums[j + 1], do
j := j + 1
res := (subarray of nums from index j + 1 to end of nums) concatenate (subarray of nums from index 0 to j of nums)
for i in range 0 to size of res - 1, do
if res[i] > res[i + 1], then
return False
return True
Example (Python)
Let us see the following implementation to get better understanding −
def solve(nums): j = 0 while (j < len(nums) - 1 and nums[j] <= nums[j + 1]): j += 1 res = nums[j + 1 : len(nums)] + nums[0:j + 1] for i in range(len(res) - 1): if res[i] > res[i + 1]: return False return True nums = [12,15,2,5,6,9] print(solve(nums))
Input
[12,15,2,5,6,9]
Output
True