Check if Array Is Sorted and Rotated
LeetCode 1752 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Count descents including the wrap-around; ≤ 1 means yes.
నేను Check if Array Is Sorted and Rotated (LeetCode 1752) ను ఇలా పరిష్కరించాను — Linear Scan ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
A sorted array rotated any amount has at most one 'drop' where a value is bigger than the next one, counting the wrap from the last element back to the first. More than one drop means it can't be a rotation of a sorted array.
Approach
- 1
Count positions where nums[i−1] > nums[i].
- 2
Also count the wrap if nums[n−1] > nums[0].
- 3
Return count ≤ 1.
నేను ఎలా పరిష్కరించాను
Count descentsPythonO(n) time · O(1) space
class Solution:
def check(self, nums):
count = 0
n = len(nums)
for i in range(1, n):
if nums[i - 1] > nums[i]:
count += 1
if nums[n - 1] > nums[0]:
count += 1
if count <= 1:
return True
return FalseCheck if Array Is Sorted and Rotated — తరచూ అడిగే ప్రశ్నలు
Check if Array Is Sorted and Rotated వెనుక ఉన్న intuition ఏమిటి?
A sorted array rotated any amount has at most one 'drop' where a value is bigger than the next one, counting the wrap from the last element back to the first. More than one drop means it can't be a rotation of a sorted array.
Check if Array Is Sorted and Rotated (LeetCode 1752) ను ఎలా పరిష్కరించాలి?
1. Count positions where nums[i−1] > nums[i]. 2. Also count the wrap if nums[n−1] > nums[0]. 3. Return count ≤ 1.
Check if Array Is Sorted and Rotated యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(1). (Accepted approach: Count descents.)
Check if Array Is Sorted and Rotated లో సాధారణ పొరపాట్లు ఏమిటి?
Equal neighbours are not drops.