Tensorum
LeetCode 1752 · Linear Scan

Check if Array Is Sorted and Rotated

LeetCode 1752 · Easy · solution, intuition & step-by-step walkthrough

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

EasyArray
55 msruntime · beats 5%
48.9 MBmemory · beats 100%
1approach
1accepted runs · last 17 Jun 2024

This is how I solved Check if Array Is Sorted and Rotated (LeetCode 1752), an easy problem from the Linear Scan pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a 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.

How I solved it

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
Loading the step-through…

Check if Array Is Sorted and Rotated — FAQ

What is the intuition behind Check if Array Is Sorted and Rotated?

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.

How do you solve 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.

What is the time and space complexity of Check if Array Is Sorted and Rotated?

Time: O(n). Space: O(1). (Accepted approach: Count descents.)

What are common mistakes in Check if Array Is Sorted and Rotated?

Equal neighbours are not drops.