- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 Questions & Answers
- Check if an array is sorted and rotated in Python
- Check if an array is sorted and rotated in C++
- 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
- How to check whether an array is a true array in JavaScript?
- How to check whether an array is empty using PHP?
- Find the Rotation Count in Rotated Sorted array in C++
- Write a Golang program to check whether a given array is sorted or not (Using Bubble Sort Technique)
- Count rotations in sorted and rotated linked list in C++

Advertisements