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
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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.