Check if Array is Sorted and Rotated in Java

DSA Series — Day 1 : Problem 3 | Arrays Problem: Check if Array Is Sorted and Rotated 🔹 Problem Understanding: An array is considered sorted and rotated if it was originally sorted in non-decreasing order and then rotated some number of times (including zero). 🔹 Approach: Traverse the array and track the number of times the order decreases (a “dip”). A valid sorted & rotated array can have at most one dip. After the dip, ensure remaining elements do not violate the circular sorted order by comparing with the first element. 🔹 Why this works: A sorted array rotated once will show exactly one break in order. More than one break means the array cannot be derived from a sorted sequence. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(1) 🔹 Java Implementation: ( Text / Image ) class Solution { public boolean check(int[] nums) { boolean dipAllow = true; for (int i = 1; i < nums.length; i++) { if (nums[i] < nums[i - 1]) { if (dipAllow) dipAllow = false; else return false; } if (!dipAllow && (nums[i] > nums[0] || nums[nums.length - 1] > nums[0])) { return false; } } return true; } } 🔹 Key Insight: The core idea is limiting the array to only one order violation. Anything beyond that breaks the definition of sorted rotation. 📈 Continuing my daily DSA problem-solving series. #DSA #Arrays #Java #ProblemSolving #StriversA2Z #CodingJourney

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories