Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created February 2, 2025 22:21
Show Gist options
  • Save Ifihan/b9c96d2e7ede78115d4d430e3f8f3b29 to your computer and use it in GitHub Desktop.
Save Ifihan/b9c96d2e7ede78115d4d430e3f8f3b29 to your computer and use it in GitHub Desktop.
Check if Array Is Sorted and Rotated

Question

Approach

I approached the problem by iterating through the array and compare each element with its next neighbor. I then compare the last element with the first.

As I iterate, every time I encounter a situation where the current element is greater than the next, I increase a counter. If this counter exceeds one, I immediately know the array couldn’t have come from a sorted array that was simply rotated, and I return false. If I complete the loop and find one or no drops, I return true.

Implementation

class Solution:
    def check(self, nums: List[int]) -> bool:
        drops = 0
        n = len(nums)

        for i in range(n):
            if nums[i] > nums[(i + 1) % n]:
                drops += 1
                if drops > 1:
                    return False
                    
        return True

Complexities

  • Time: O(n).
  • Space: O(1).
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment