Check if Array Is Sorted and Rotated

Pattern: Traversal and in-place tricks

easy

An array is a rotated sorted array exactly when, going round it once in a circle, it steps down at most once.

The problem

You are given an array nums of 1 to 100 whole numbers, each from 1 to 100, possibly with repeats. Return true if it could have been made by taking an array sorted in non-decreasing order and rotating it, that is, moving some number of elements (possibly none) from the front to the back. For example, [3, 4, 5, 1, 2] is [1, 2, 3, 4, 5] rotated, so the answer is true. [2, 1, 3, 4] cannot be made this way, so the answer is false.

The function name check matches LeetCode. Use the link above for the exact statement.

Think first

  • Write the sorted array [1, 2, 3, 4, 5] on a circle. Where does the value go down as you walk round it?
  • Now rotate it to [3, 4, 5, 1, 2]. How many places step down?
  • Why must the walk also compare the last element with the first?

Hints

    Brute force, and why it fails

    Sort a copy of the array, then try every rotation of the original and compare it with the sorted copy. That is n rotations of n comparisons each, O(n²), which is fine for 100 elements but wasteful. Counting drops in one pass gives the same answer in O(n).

    The key insight

    Rotation only changes where you start reading the circle. A sorted circle goes down exactly once (or never, if all values are equal), so count the drops round the circle and accept at most one.

    Dry run

    30 
    41 
    52 
    13 
    24 
    drops0

    nums = [3, 4, 5, 1, 2]. Walk round the array, comparing each element with the next one and wrapping from the end back to the start. Count the drops.

    Step 1 of 7

    The plan

    n = length(nums)
    drops = 0
    for i from 0 to n - 1:
        if nums[i] > nums[(i + 1) mod n]:   # compare with the next, wrapping round
            drops = drops + 1
    return drops <= 1
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass with one comparison per element, and a single counter.

    Edge cases

    • One element: it compares with itself, finds no drop, and returns true.
    • All equal such as [1, 1, 1]: no drops, true.
    • Already sorted such as [1, 2, 3]: the only drop is the wrap from 3 back to 1, so true (rotated by zero).
    • [2, 1]: one drop from 2 to 1, and the wrap from 1 to 2 is not a drop, so true.
    • [2, 1, 3, 4]: one drop from 2 to 1 and one from 4 back to 2, so false.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean check(int[] nums) {
            int n = nums.length;
            int drops = 0;
            for (int i = 0; i < n; i++) {
                if (nums[i] > nums[(i + 1) % n]) {   // compare with the next, wrapping around
                    drops++;
                }
            }
            return drops <= 1;
        }
    }

    C++

    class Solution {
    public:
        bool check(vector<int>& nums) {
            int n = static_cast<int>(nums.size());
            int drops = 0;
            for (int i = 0; i < n; i++) {
                if (nums[i] > nums[(i + 1) % n]) {   // compare with the next, wrapping around
                    drops++;
                }
            }
            return drops <= 1;
        }
    };

    Python

    class Solution:
        def check(self, nums: list[int]) -> bool:
            n = len(nums)
            drops = 0
            for i in range(n):
                if nums[i] > nums[(i + 1) % n]:   # compare with the next, wrapping around
                    drops += 1
            return drops <= 1

    Common mistakes

    • Forgetting the wrap-around comparison, which accepts [2, 1, 3, 4].
    • Using >= instead of >, which counts equal neighbours as drops and rejects [1, 1, 1].
    • Accepting only exactly one drop, which rejects arrays where all values are equal.

    Similar problems