Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 1752 · Linear Scan

Check if Array Is Sorted and Rotated

LeetCode 1752 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Count descents including the wrap-around; ≤ 1 means yes.

सोपाArray

मी 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. 1

    Count positions where nums[i−1] > nums[i].

  2. 2

    Also count the wrap if nums[n−1] > nums[0].

  3. 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 False
स्टेप-थ्रू लोड होत आहे…

Check 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.