Leetcode 1752: Check if Array Is Sorted and Rotated

grid47
grid47
Exploring patterns and algorithms
May 15, 2024 5 min read

You are given an array nums. The array is originally sorted in non-decreasing order and then rotated some number of positions (including zero). Your task is to determine if the array could have been rotated from a sorted array. Return true if the array can be rotated to become sorted, and false otherwise.
Problem
Approach
Steps
Complexity
Input: The input consists of a single array `nums` of length `n`.
Example: Input: nums = [4,5,6,7,1,2,3]
Constraints:
• 1 <= nums.length <= 100
• 1 <= nums[i] <= 100
Output: Return `true` if the array can be rotated to become sorted in non-decreasing order. Otherwise, return `false`.
Example: Output: true
Constraints:
• The returned value will be either true or false.
Goal: Determine if the array can be rotated to match a sorted sequence.
Steps:
• 1. Traverse the array from the first to the last element.
• 2. Count how many times the array decreases (i.e., when `nums[i] > nums[i+1]`).
• 3. If there is more than one decrease, the array cannot be a rotated sorted array, and return `false`.
• 4. If there is zero or one decrease, return `true`.
Goal: The solution should handle arrays of size up to 100 elements efficiently.
Steps:
• Ensure that the solution works in linear time, O(n).
Assumptions:
• The array can contain duplicate elements.
• There is no need to handle edge cases for empty arrays as the length of `nums` is always at least 1.
Input: Input: nums = [3,4,5,1,2]
Explanation: This array can be viewed as a rotation of [1,2,3,4,5]. Hence, the array can be rotated back into a sorted array, and the output is `true`.

Input: Input: nums = [2,1,3,4]
Explanation: This array cannot be rotated into a sorted array because there is a drop between `2` and `1` and it cannot be rotated to become sorted. Hence, the output is `false`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus