#1752
Check if Array Is Sorted and Rotated
EasyArrayArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking every rotation, we can find the number of times the array 'drops' from a higher to a lower value. If it drops more than once, it can't be a rotated sorted array.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a count variable to track the number of drops.
- 2Step 2: Loop through the array and compare each element with the next one, counting how many times the current element is greater than the next.
- 3Step 3: If the count is more than 1, return false. Otherwise, return true.
solution.py7 lines
1def check(nums):
2 count = 0
3 n = len(nums)
4 for i in range(n):
5 if nums[i] > nums[(i + 1) % n]:
6 count += 1
7 return count <= 1ℹ
Complexity note: We only loop through the array once, making it O(n) time complexity, and we use a constant amount of space.
- 1An array can only have one drop point to be considered a rotated sorted array.
- 2Duplicates do not affect the sorted nature but can complicate the drop counting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.