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.