Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 1752: Check if Array Is Sorted and Rotated

Array

LeetCode 1752 Solution 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)

:

LeetCode 1752 Solutions in Java, C++, Python

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];
    }
}

Interactive Code Editor for LeetCode 1752

Improve Your LeetCode 1752 Solution

Use the editor below to refine the provided solution for LeetCode 1752. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems