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
Rotation Break Point VisualizationOriginal Sorted Array12345Break Points: 0After Rotating by 3 Positions34512BREAK: 5 > 1Break Points: 1Algorithm Logic1. Count break points where nums[i] > nums[(i+1) % n]2. A valid rotated sorted array has exactly 0 or 1 break points: โ€ข 0 breaks = already sorted (rotation by 0) โ€ข 1 break = rotated sorted array โ€ข 2+ breaks = invalid (cannot be created by rotation)
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!
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen