Check if Array Is Sorted and Rotated - Problem

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.

There may be duplicates in the original array.

Note: An array A rotated by x positions results in an array B of the same length such that B[i] == A[(i+x) % A.length] for every valid index i.

Input & Output

Example 1 — Sorted and Rotated
$ Input: nums = [2,1,3,4]
Output: true
💡 Note: The array [1,2,3,4] was rotated by 3 positions to get [2,1,3,4]. Original: [1,2,3,4] → Rotate right by 3 → [2,1,3,4]. Only one break point at position 0→1.
Example 2 — Not Sorted Even After Rotation
$ Input: nums = [3,4,5,1,2]
Output: true
💡 Note: Original sorted array [1,2,3,4,5] was rotated. Only one break point where 5 > 1, so it's valid.
Example 3 — Multiple Break Points
$ Input: nums = [2,1,3,4,5,10,6,7,8]
Output: false
💡 Note: Multiple break points: 2>1, 10>6. No rotation can make this array sorted.

Constraints

  • 1 ≤ nums.length ≤ 100
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Check if Array Is Sorted and Rotated INPUT nums array: 2 i=0 1 i=1 3 i=2 4 i=3 Find break points where nums[i] > nums[i+1] 2>1 BREAK 1>3 OK 3>4 OK 4>2 BREAK Input Values: nums = [2, 1, 3, 4] Length: 4 ALGORITHM STEPS 1 Initialize counter breakCount = 0 2 Loop through array Compare nums[i] with nums[(i+1) % n] 3 Count break points If nums[i] > nums[i+1] increment breakCount 4 Return result Return breakCount <= 1 Execution Trace: i=0: 2>1? YES count=1 i=1: 1>3? NO count=1 i=2: 3>4? NO count=1 i=3: 4>2? YES count=2 Final: count=2 > 1 FINAL RESULT Break Points Found: 2 Original Sorted Array: 1 2 3 4 Rotated by 1 position: 4 1 2 3 [2,1,3,4] has 2 breaks Not a valid rotation! OUTPUT false breakCount (2) > 1 Key Insight: A sorted and rotated array can have at most ONE break point (where nums[i] > nums[(i+1)%n]). This break occurs at the rotation point. If there are 0 or 1 break points, the array is valid. Here [2,1,3,4] has 2 breaks (2>1 and 4>2), so it cannot be a sorted and rotated array. TutorialsPoint - Check if Array Is Sorted and Rotated | Count Break Points Approach
Asked in
Amazon 15 Microsoft 12 Google 8
18.5K Views
Medium Frequency
~15 min Avg. Time
892 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