
- 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
Check if an array is sorted and rotated in Python
Suppose we have an array of n unique values. We have to check whether this array is sorted and rotated anti-clockwise. Here at least one rotation is required so a fully sorted array is not considered as sorted and rotated.
So, if the input is like nums = [4,5,6,8,1,3], then the output will be True as we can rotate two times to the clockwise direction then it will be sorted like [1, 3, 4, 5, 6, 8].
To solve this, we will follow these steps −
- min_element := minimum of nums
- min_index := index of min_element in nums
- before_sorted := True
- for i in range 1 to min_index - 1, do
- if nums[i] < nums[i - 1], then
- before_sorted := False
- come out from loop
- if nums[i] < nums[i - 1], then
- after_sorted := True
- for i in range min_index + 1 to size of nums - 1, do
- if nums[i] < nums[i - 1], then
- after_sorted := False
- come out from loop
- if nums[i] < nums[i - 1], then
- if before_sorted and after_sorted are true and last element of nums < nums[0], then
- return True
- otherwise,
- return False
Let us see the following implementation to get better understanding −
Example
def solve(nums): min_element = 999999 min_index = -1 min_element = min(nums) min_index = nums.index(min_element) before_sorted = True for i in range(1, min_index): if nums[i] < nums[i - 1]: before_sorted = False break after_sorted = True for i in range(min_index + 1, len(nums)): if nums[i] < nums[i - 1]: after_sorted = False break if before_sorted and after_sorted and nums[-1] < nums[0]: return True else: return False nums = [4,5,6,8,1,3] print(solve(nums))
Input
[4,5,6,8,1,3]
Output
True
- Related Articles
- Check if an array is sorted and rotated in C++
- Program to check whether an array Is sorted and rotated in Python
- Search in Rotated Sorted Array in Python
- Search in Rotated Sorted Array II in Python
- C++ program to search an element in a sorted rotated array
- 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++
- Check if an array is descending, ascending or not sorted in JavaScript
- Find Minimum in Rotated Sorted Array II in C++
- Check If a Number Is Majority Element in a Sorted Array in Python
- Program to check if an array is sorted or not (Iterative and Recursive) in C
- Check if reversing a sub array make the array sorted in Python
- Finding smallest element in a sorted array which is rotated in JavaScript
- Check if array can be sorted with one swap in Python

Advertisements