Check if Array Is Sorted and Rotated - Problem
Imagine you have a perfectly sorted array, but someone rotated it by moving some elements from the front to the back. Your task is to determine if an array could have been created this way!
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.
What does rotation mean? When we rotate an array by x positions, we take the first x elements and move them to the end. For example:
- Original:
[1, 2, 3, 4, 5] - Rotate by 2:
[3, 4, 5, 1, 2]
Note: The original array may contain duplicates, and rotating by 0 positions means the array stays the same.
Input & Output
example_1.py โ Basic Rotation
$
Input:
nums = [3,4,5,1,2]
โบ
Output:
true
๐ก Note:
The original array was [1,2,3,4,5] rotated 3 times to the right, giving us [3,4,5,1,2].
example_2.py โ Invalid Array
$
Input:
nums = [2,1,3,4]
โบ
Output:
false
๐ก Note:
There's no rotation of a sorted array that would give us [2,1,3,4]. This has 2 break points: 2>1 and 4>2 (circular).
example_3.py โ Already Sorted
$
Input:
nums = [1,2,3]
โบ
Output:
true
๐ก Note:
The array is already sorted (rotation by 0), so it's a valid rotated sorted array.
Constraints
- 1 โค nums.length โค 100
- -104 โค nums[i] โค 104
- The array may contain duplicates
Visualization
Tap to expand
Understanding the Visualization
1
Original Sorted Array
Start with [1,2,3,4,5] - perfectly sorted with no breaks
2
Apply Rotation
Rotate by 3 positions โ [3,4,5,1,2] creates one break at 5โ1
3
Count Break Points
Scan array: 3โค4โ, 4โค5โ, 5>1โ, 1โค2โ, 2โค3โ = 1 break total
4
Validation
Since break count = 1 โค 1, this is a valid rotated sorted array
Key Takeaway
๐ฏ Key Insight: A sorted array rotated by any amount will have exactly one position where the order 'breaks' (larger number followed by smaller). Count these breaks in O(n) time!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code