Determining whether an array is sorted and rotated is a classic problem in computer science that frequently appears in technical interviews and competitive programming. A sorted and rotated array is essentially a sorted array that has been shifted cyclically a certain number of times. Day to day, it tests a developer's understanding of array properties, binary search modifications, and edge-case handling. To give you an idea, the array [1, 2, 3, 4, 5] rotated three times becomes [4, 5, 1, 2, 3]. The challenge lies in verifying this specific structure efficiently, ideally in logarithmic time complexity.
Understanding the Core Concept
Before diving into algorithms, it is crucial to define exactly what constitutes a sorted and rotated array. An array meets this criteria if it can be split into two contiguous subarrays, both of which are individually sorted in non-decreasing order, and every element in the first subarray is greater than or equal to every element in the second subarray.
Visually, a standard sorted array looks like a straight line sloping upward. , 5 followed by 1 in the example above). But this pivot is the only place in the array where the next element is smaller than the current element (e. g.A sorted and rotated array looks like two upward slopes joined at a pivot point—the point of rotation. In a perfectly sorted array with no rotation, this "drop" does not exist, or it exists conceptually between the last and first element The details matter here. Less friction, more output..
Key characteristics to identify:
- At most one inversion point: There is exactly one index
isuch thatarr[i] > arr[i+1]. If the array is fully sorted (zero rotations), this count is zero. - Circular continuity: The last element must be less than or equal to the first element (unless the array is not rotated at all).
The Linear Scan Approach: Simplicity First
The most intuitive method to check if an array is sorted and rotated is a linear scan. This approach runs in O(N) time and O(1) space, making it perfectly acceptable for many practical scenarios where N is not massive.
Algorithm Steps:
- Initialize a counter
countto zero. This tracks the number of timesarr[i] > arr[i+1]. - Iterate through the array from index
0toN-2. - If
arr[i] > arr[i+1], incrementcount. - After the loop, check the circular condition: if
arr[N-1] > arr[0], incrementcount. - Verdict: If
count <= 1, the array is sorted and rotated. Otherwise, it is not.
Why this works:
A sorted array has count = 0 (the circular check arr[N-1] > arr[0] is true, so count becomes 1? Wait. Let's refine).
- Case 1: Sorted, not rotated.
[1, 2, 3, 4, 5]. Linear scan finds 0 drops. Circular check:5 > 1is true. Count = 1. Valid. - Case 2: Sorted and rotated.
[3, 4, 5, 1, 2]. Linear scan finds 1 drop (5 > 1). Circular check:2 > 3is false. Count = 1. Valid. - Case 3: Not sorted.
[3, 5, 4, 1, 2]. Linear scan finds drops at5>4and4>1(wait,4>1is a drop). Count = 2. Invalid.
Correction on logic: The condition count <= 1 holds perfectly.
Python Implementation (Linear):
def check_sorted_rotated_linear(arr):
n = len(arr)
if n <= 1:
return True
count = 0
for i in range(n - 1):
if arr[i] > arr[i + 1]:
count += 1
# Check circular wrap-around
if arr[n - 1] > arr[0]:
count += 1
return count <= 1
This method is reliable, handles duplicates effortlessly, and is easy to explain during an interview. On the flip side, if the constraint demands O(log N) time, we must turn to Binary Search Still holds up..
The Binary Search Approach: Achieving O(log N)
Finding the pivot point (the minimum element) in a sorted and rotated array is a standard Binary Search problem. Note: Standard binary search for the pivot assumes distinct elements. Once the pivot is found, verifying the sorted nature of the two halves confirms the structure. Handling duplicates in O(log N) is theoretically impossible in the worst case (degrades to O(N)), but we can optimize for average cases.
Finding the Pivot (Minimum Element)
The pivot is the only element smaller than its previous element. In a rotated array, the right half of the pivot is sorted, and the left half is sorted Small thing, real impact..
Binary Search Logic for Pivot:
low = 0,high = N - 1.- While
low <= high:- If
arr[low] <= arr[high]: The subarray is already sorted.arr[low]is the minimum. Returnlow. mid = low + (high - low) // 2.next = (mid + 1) % N,prev = (mid - 1 + N) % N.- If
arr[mid] <= arr[next]andarr[mid] <= arr[prev]: Found pivot. Returnmid. - If
arr[mid] <= arr[high]: Right half is sorted, pivot must be in left half.high = mid - 1. - Else: Left half is sorted, pivot must be in right half.
low = mid + 1.
- If
Verification Step
Once the pivot index p is found:
- Check if subarray
arr[0...p-1]is sorted. - Check if subarray
arr[p...N-1]is sorted. - Check if
arr[N-1] <= arr[0](unlessp == 0, meaning no rotation).
This verification is technically O(N) in the worst case if done naively, defeating the purpose. That said, the existence of a single pivot found via Binary Search is the proof for distinct elements. If the Binary Search logic successfully terminates finding a single pivot where neighbors are larger, the array structure is validated by the properties of the search itself.
Easier said than done, but still worth knowing.
Refined O(log N) Logic for Distinct Elements:
If the Binary Search finds a valid pivot index p (where arr[p] is min), the array is sorted and rotated. If the search concludes low == 0 and arr[low] <= arr[high] initially, it's sorted (non-rotated). If the search fails the neighbor checks at every step without finding a pivot, the array is not sorted and rotated.
Python Implementation (Binary Search - Distinct Elements):
def find_pivot(arr, low, high):
n = len(arr)
while low <= high:
# Case 1: Subarray is already sorted
if arr[low] <= arr[high]:
return low
mid = low + (high - low) // 2
next_idx = (mid + 1) % n
prev_idx = (mid - 1 + n) % n
# Check if mid is pivot
if arr[mid] <= arr[next_idx] and arr[mid] <= arr[prev_idx]:
return mid
# Decide which half to go to
if arr[mid] <= arr[high]:
high =