Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if it is possible to sort the array after rotating it in Python
Sometimes we have an array that can be sorted by rotating it. Rotation means taking some contiguous elements from the end and moving them to the front. We need to check if such a rotation can make the array sorted.
For example, the array [4,5,6,1,2,3] can be sorted by rotating the last three elements [1,2,3] to the front, giving us [1,2,3,4,5,6].
Algorithm
The approach works by finding the rotation point where the sorted order breaks ?
- If the array is already sorted, return
True - Find the first position where
nums[i] > nums[i + 1](rotation point) - Check if the remaining part is sorted
- Verify that rotating would create a valid sorted array
Example
Let's implement the solution to check if rotation can sort the array ?
def solve(nums):
n = len(nums)
# Check if already sorted
if all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)):
return True
else:
status = True
# Find the first break point
for i in range(n - 1):
if nums[i] > nums[i + 1]:
break
i += 1
# Check if remaining part is sorted
for k in range(i, n - 1):
if nums[k] > nums[k + 1]:
status = False
break
if not status:
return False
else:
# Check if rotation would work
if nums[n - 1] <= nums[0]:
return True
return False
# Test the function
nums = [4, 5, 6, 1, 2, 3]
print(solve(nums))
True
How It Works
Let's trace through the example [4,5,6,1,2,3] ?
def solve_with_trace(nums):
n = len(nums)
print(f"Input array: {nums}")
# Check if already sorted
if all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)):
print("Array is already sorted")
return True
print("Array is not sorted, checking rotation possibility...")
# Find the break point
for i in range(n - 1):
if nums[i] > nums[i + 1]:
print(f"Break point found at index {i}: {nums[i]} > {nums[i + 1]}")
break
i += 1
print(f"Checking if elements from index {i} onwards are sorted...")
# Check remaining part
for k in range(i, n - 1):
if nums[k] > nums[k + 1]:
print(f"Not sorted at index {k}: {nums[k]} > {nums[k + 1]}")
return False
print("Remaining part is sorted")
# Check rotation validity
if nums[n - 1] <= nums[0]:
print(f"Rotation valid: last element {nums[n - 1]} <= first element {nums[0]}")
return True
else:
print(f"Rotation invalid: last element {nums[n - 1]} > first element {nums[0]}")
return False
# Test cases
test_cases = [[4, 5, 6, 1, 2, 3], [2, 1, 3, 4], [1, 2, 3, 4, 5]]
for nums in test_cases:
result = solve_with_trace(nums)
print(f"Result: {result}\n")
Input array: [4, 5, 6, 1, 2, 3] Array is not sorted, checking rotation possibility... Break point found at index 2: 6 > 1 Checking if elements from index 3 onwards are sorted... Remaining part is sorted Rotation valid: last element 3 <= first element 4 Result: True Input array: [2, 1, 3, 4] Array is not sorted, checking rotation possibility... Break point found at index 0: 2 > 1 Checking if elements from index 1 onwards are sorted... Remaining part is sorted Rotation invalid: last element 4 > first element 2 Result: False Input array: [1, 2, 3, 4, 5] Array is already sorted Result: True
Key Points
- A rotated sorted array has at most one break point
- After the break point, elements must be in ascending order
- The last element must be ? first element for valid rotation
- Time complexity: O(n), Space complexity: O(1)
Conclusion
This algorithm efficiently checks if an array can be sorted through rotation by finding the break point and validating the rotation condition. The key insight is that a valid rotated sorted array has exactly one descending transition.
