π₯ LeetCode 1752 - Check if Array Is Sorted and Rotated | May 23 POTD
π Problem:
Given an array nums, return true if the array was originally sorted
in non-decreasing order and then rotated some number of positions
(including zero). Otherwise return false.
Duplicates are allowed.
Example 1: nums = [3,4,5,1,2] β true (rotated [1,2,3,4,5] by 2)
Example 2: nums = [2,1,3,4] β false (no rotation produces this)
Example 3: nums = [1,2,3] β true (rotated by 0 positions)
π‘ Approach: Inversion Count
Key Insight: A sorted rotated array can have AT MOST one inversion point!
What is an inversion?
β A position where nums[i] is less than nums[i-1]
(i.e. the sequence drops down)
In a valid sorted rotated array:
β There can be at most 1 drop in the middle (the rotation point)
β BUT we also check if nums[0] is less than nums[len-1]
because wrapping around also creates an inversion
β If total inversions is more than 1, return false
Step by step:
β Count inversions across the array
β Also check if nums[0] is less than nums[len-1] as wrap inversion
β If countInversion is greater than or equal to 2, return false
β Else return true
β± Complexity:
- Time: O(n) β single pass through the array
- Space: O(1) β no extra space
β Difficulty: Easy
π May 23, 2025 β Problem of the Day
π Perfect follow-up to LC 33 and LC 153 β Rotated Array series!
βββββββββββββββββββββββ
π Problem Link:
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/
#leetcode #java #inversioncount #dsa #leetcodedaily #potd
#leetcodeEasy #competitiveprogramming #may23potd #leetcode1752
#rotatedarray #sortedarray #oneliner #mustwatch