LeetCode 1752: Check if Array Is Sorted and Rotated Solution

Master LeetCode problem 1752 (Check if Array Is Sorted and Rotated), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1752. Check if Array Is Sorted and Rotated

Easy

Problem Explanation

Explanation:

To solve this problem, we can iterate through the given array and find the point where the array is not in non-decreasing order. If we find more than one such point, then the array cannot be sorted and rotated. If we find exactly one such point, then we check if rotating the array at that point gives us the original sorted array.

  • Find the point where the array is not in non-decreasing order.
  • If there is no such point, the array is already sorted, return true.
  • If there is one such point, check if rotating the array at that point gives the original sorted array.
  • If yes, return true. Otherwise, return false.

Time Complexity: O(n), where n is the number of elements in the given array. Space Complexity: O(1)

:

Solution Code

class Solution {
    public boolean check(int[] nums) {
        int n = nums.length;
        int count = 0;

        for (int i = 0; i < n; i++) {
            if (nums[i] > nums[(i + 1) % n]) {
                count++;
            }
            if (count > 1) {
                return false;
            }
        }

        return count == 0 || nums[0] >= nums[n - 1];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1752 (Check if Array Is Sorted and Rotated)?

This page provides optimized solutions for LeetCode problem 1752 (Check if Array Is Sorted and Rotated) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1752 (Check if Array Is Sorted and Rotated)?

The time complexity for LeetCode 1752 (Check if Array Is Sorted and Rotated) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1752 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1752 in Java, C++, or Python.

Back to LeetCode Solutions