Check if Array Is Sorted and Rotated - Complete Solution Guide
Check if Array Is Sorted and Rotated is LeetCode problem 1752, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given an array nums , return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero) . Otherwise, return false . There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that B[i] == A[(i+x) % A.length] for every valid index i . Example 1: Input: nums = [3,4,5,1,2] Output: true Explanation: [1,2,3,4,5] is the original sorted array. You can rotate the array b
Detailed Explanation
The problem asks whether a given array can be obtained by rotating a sorted array (in non-decreasing order). The input is an array of integers `nums`. The output is a boolean value: `true` if the array is a rotated version of a sorted array, and `false` otherwise. Duplicate numbers are allowed in the input array. The rotation can be zero positions (meaning the array is already sorted).
Solution Approach
The solution uses a single pass through the array to count the number of times an element is greater than its subsequent element. It leverages the modulo operator to wrap around from the end of the array to the beginning for the last element comparison. If this count is less than or equal to 1, it means the array could be a rotated version of a sorted array; otherwise, it's not.
Step-by-Step Algorithm
- Step 1: Initialize a `count` variable to 0. This variable will track the number of times an element is greater than its successor.
- Step 2: Iterate through the array using a `for` loop. For each element `nums[i]`, compare it to `nums[(i + 1) % n]`, where `n` is the length of the array. The modulo operator ensures correct comparison for the last element.
- Step 3: If `nums[i] > nums[(i + 1) % n]`, increment the `count`.
- Step 4: After the loop, check if `count <= 1`. If true, return `true` (rotated sorted array); otherwise, return `false`.
Key Insights
- Insight 1: A sorted array, when rotated, will have at most one point of discontinuity where the order changes from decreasing to increasing. This is because a single rotation only introduces one such change.
- Insight 2: We can efficiently detect this discontinuity by iterating through the array and counting the number of times a number is greater than the next number. If this count exceeds 1, it's not a rotated sorted array.
- Insight 3: Handling the circularity of the array when comparing the last element with the first is crucial. The modulo operator (`%`) is used to elegantly handle this.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array.
Companies
Asked at: SoundHound, tcs.