
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to check whether an array Is sorted and rotated in Python
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
- Related Articles
- Check if an array is sorted and rotated in Python
- Check if an array is sorted and rotated in C++
- C++ program to search an element in a sorted rotated array
- Search in Rotated Sorted Array in Python
- Search in Rotated Sorted Array II in Python
- Maximum element in a sorted and rotated array in C++
- Search in Rotated Sorted Array II in C++
- Find Minimum in Rotated Sorted Array in C++
- Program to check if an array is sorted or not (Iterative and Recursive) in C
- Find Minimum in Rotated Sorted Array II in C++
- Finding smallest element in a sorted array which is rotated in JavaScript
- Find the Rotation Count in Rotated Sorted array in C++
- Program to find maximum weighted sum for rotated array in Python
- Write a Golang program to check whether a given array is sorted or not (Using Bubble Sort Technique)
- How to check whether an array is a true array in JavaScript?

Advertisements