
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Check If Array Can Be Sorted After Rotation in Python
Suppose we have a list of numbers called nums, we have to check whether we can sort nums or not by using rotation. By rotation we can shift some contiguous elements from the end of nums and place it in the front of the array.
So, if the input is like nums = [4,5,6,1,2,3], then the output will be True as we can sort by rotating last three elements and send them back to first.
To solve this, we will follow these steps −
- n := size of nums
- if nums is sorted, then
- return True
- otherwise,
- status := True
- for i in range 0 to n - 2, do
- if nums[i] > nums[i + 1], then
- come out from loop
- if nums[i] > nums[i + 1], then
- i := i + 1
- for k in range i to n - 2, do
- if nums[k] > nums[k + 1], then
- status := False
- come out from loop
- if nums[k] > nums[k + 1], then
- if status is false, then
- return False
- otherwise,
- if nums[n - 1] <= nums[0], then
- return True
- return False
- if nums[n - 1] <= nums[0], then
Example
Let us see the following implementation to get better understanding −
def solve(nums): n = len(nums) if all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)): return True else : status = True for i in range(n - 1) : if nums[i] > nums[i + 1] : break i += 1 for k in range(i, n - 1) : if nums[k] > nums[k + 1]: status = False break if not status: return False else : if nums[n - 1] <= nums[0]: return True return False nums = [4,5,6,1,2,3] print(solve(nums))
Input
[4,5,6,1,2,3]
Output
True
Advertisements