{"slug": "leetcode-solution-1752-check-if-array-is-sorted-and-rotated", "title": "LeetCode Solution: 1752. Check if Array Is Sorted and Rotated", "summary": "The article explains LeetCode problem 1752, which asks whether a given array could have been a non-decreasing sorted array that was then rotated. The key insight is that a valid sorted and rotated array will have at most one \"descent\" (where a previous element is greater than the next) when iterating through the array, including the wrap-around comparison between the last and first elements. The solution involves counting these descents and returning true if the count is 1 or less.", "body_md": "# 🔄 LeetCode 1752: Can You Un-Rotate This Array? (A Beginner's Guide)\n\nHey there, fellow coders! 👋 Vansh2710 here, ready to demystify another exciting LeetCode challenge. Today, we're tackling problem 1752: \"Check if Array Is Sorted and Rotated.\" Sounds a bit like a puzzle, right? Don't worry, we'll break it down piece by piece and uncover a super elegant solution!\n\nThis problem is a fantastic way to sharpen your array manipulation and logical thinking skills. It might seem tricky at first, but with a simple trick, it becomes incredibly straightforward. Let's dive in!\n\n### What's the Problem All About? 🧐\n\nImagine you have a perfectly sorted list of numbers, like `[1, 2, 3, 4, 5]`\n\n.\n\nNow, imagine you *rotate* it. This means you take some elements from the beginning and move them to the end, keeping their relative order.\n\nFor example, if you rotate `[1, 2, 3, 4, 5]`\n\nby 2 positions:\n\n`[1, 2, 3, 4, 5]`\n\n- Take\n`1, 2`\n\nand move them to the end:`[3, 4, 5, 1, 2]`\n\nThe problem asks: **Given an array nums, can we tell if it could have been originally sorted (non-decreasingly) and then rotated some number of times (even zero rotations)?**\n\n**Key things to remember:**\n\n-\n**Non-decreasing order:**`[1, 2, 2, 3]`\n\nis sorted.`[3, 2, 1]`\n\nis not. -\n**Rotation:** Can be any number of positions, including 0 (no rotation). -\n**Duplicates are allowed:** This is an important detail!`[3, 4, 5, 5, 1, 2]`\n\ncould be`[1, 2, 3, 4, 5, 5]`\n\nrotated.\n\n**Let's look at examples:**\n\n-\n`nums = [3, 4, 5, 1, 2]`\n\n- Is\n`[1, 2, 3, 4, 5]`\n\nsorted? Yes. - Can\n`[1, 2, 3, 4, 5]`\n\nbe rotated to get`[3, 4, 5, 1, 2]`\n\n? Yes, rotate by 2 positions. -\n**Output:**`true`\n\n- Is\n-\n`nums = [2, 1, 3, 4]`\n\n- If sorted, it would be\n`[1, 2, 3, 4]`\n\n. - Can\n`[1, 2, 3, 4]`\n\nbe rotated to`[2, 1, 3, 4]`\n\n? No. The`2, 1`\n\npart breaks the sorted order that a single rotation would maintain. -\n**Output:**`false`\n\n- If sorted, it would be\n-\n`nums = [1, 2, 3]`\n\n- Is it sorted? Yes.\n- Can it be rotated to get\n`[1, 2, 3]`\n\n? Yes, 0 rotations. -\n**Output:**`true`\n\n### The \"Aha!\" Moment - Our Intuition ✨\n\nThink about a truly sorted array like `[1, 2, 3, 4, 5]`\n\n. If you go from left to right, `nums[i-1]`\n\nis always less than or equal to `nums[i]`\n\n. There are no \"drops\" or \"descents\" in value.\n\nNow, consider a *rotated* sorted array: `[3, 4, 5, 1, 2]`\n\n.\n\nIf you scan this, you'll see:\n\n-\n`3 <= 4`\n\n(OK) -\n`4 <= 5`\n\n(OK) -\n`5 > 1`\n\n(AHA! A**descent**!) -\n`1 <= 2`\n\n(OK)\n\nNotice something? There's only *one place* where the non-decreasing order is broken: `5`\n\nfollowed by `1`\n\n. This \"break\" is exactly where the rotation happened! The elements `[1, 2]`\n\nwere moved from the beginning to the end, creating this single drop in value.\n\nWhat if there are *two* descents? For example, `[2, 1, 3, 4]`\n\n.\n\n-\n`2 > 1`\n\n(Descent 1) -\n`1 <= 3`\n\n(OK) -\n`3 <= 4`\n\n(OK) Here, we have one descent. What about the wrap-around?`4 > 2`\n\n? No. Actually, if the original array was`[1,2,3,4]`\n\n, and we rotated it, we would*never*get`[2,1,3,4]`\n\n. A single rotation implies that*all*elements after the rotation point are smaller than*all*elements before it. The only \"break\" can be at the rotation point.\n\nSo, the core intuition is: **A sorted and rotated array will have at most ONE \"descent\" (where nums[i-1] > nums[i]) when you iterate through it.**\n\n**Wait, what about the wrap-around?**\n\nConsider `[4, 5, 1, 2, 3]`\n\n.\n\n`4 <= 5`\n\n(OK)\n\n`5 > 1`\n\n(Descent!)\n\n`1 <= 2`\n\n(OK)\n\n`2 <= 3`\n\n(OK)\n\nHere, we have one descent. But also, `nums[n-1]`\n\n(which is `3`\n\n) is less than `nums[0]`\n\n(which is `4`\n\n). This comparison also forms part of the \"break\" in sorted order, conceptually wrapping around the array. Our descent counter needs to account for this.\n\n**Revised Intuition:** Count the number of times `nums[i-1] > nums[i]`\n\n. This count should be at most 1, *including* the wrap-around comparison between the last and first elements.\n\n### Step-by-Step Approach 🚶♂️\n\nLet's formalize our intuition into a clear algorithm:\n\n**Initialize a counter:** We'll need a variable, let's call it`descentCount`\n\n, and set it to`0`\n\n. This counter will track how many times we find`nums[i-1] > nums[i]`\n\n.-\n**Iterate through the array:** Loop from the second element (`i = 1`\n\n) up to the end of the array (`nums.size() - 1`\n\n).- In each iteration, compare the current element (\n`nums[i]`\n\n) with the previous one (`nums[i-1]`\n\n). - If\n`nums[i-1] > nums[i]`\n\n, it means we've found a \"descent\" or a break in the non-decreasing order. Increment`descentCount`\n\n.\n\n- In each iteration, compare the current element (\n-\n**Check the wrap-around case:** After the loop finishes, we need to consider the connection between the*last*element and the*first*element. In a rotated sorted array, if there was a rotation, the last element might be greater than the first element (e.g., in`[3, 4, 5, 1, 2]`\n\n,`nums[4]`\n\n(which is`2`\n\n) is less than`nums[0]`\n\n(which is`3`\n\n). This doesn't add a descent.\n\nHowever, in`[1,2,3]`\n\n(0 rotations),`nums[2]`\n\n(3) is greater than`nums[0]`\n\n(1).\n\nLet's re-evaluate: The descent is where the sequence*decreases*.-\n`[3, 4, 5, 1, 2]`\n\n->`5 > 1`\n\n(1 descent)-\n`nums[n-1]`\n\n(2) is*not*greater than`nums[0]`\n\n(3).\n\n-\n-\n`[1, 2, 3]`\n\n-> No descents.-\n`nums[n-1]`\n\n(3) is*not*greater than`nums[0]`\n\n(1).\n\n-\n-\n`[2, 1, 3, 4]`\n\n->`2 > 1`\n\n(1 descent)-\n`nums[n-1]`\n\n(4) is*not*greater than`nums[0]`\n\n(2).\n\n-\n\nMy logic for the wrap-around check in the solution code is\n\n`if (nums[n-1] > nums[0])`\n\n. Let's trace it with examples:-\n`[3,4,5,1,2]`\n\n(n=5)- Loop:\n`(5 > 1)`\n\n->`descentCount = 1`\n\n- Wrap-around:\n`nums[4]`\n\n(2)`>`\n\n`nums[0]`\n\n(3) is`false`\n\n. - Total\n`descentCount = 1`\n\n. Return`true`\n\n. Correct.\n\n- Loop:\n\n-\n\n``` php\n*   `[2,1,3,4]` (n=4)\n    *   Loop: `(2 > 1)` -> `descentCount = 1`\n    *   Wrap-around: `nums[3]` (4) `>` `nums[0]` (2) is `true`. -> `descentCount = 2`.\n    *   Total `descentCount = 2`. Return `false`. Correct. (Because original `[1,2,3,4]` cannot be rotated to `[2,1,3,4]`. It has two \"breaks\" if you consider it circular: `2->1` and `4->2` (conceptual circular link)).\n\n*   `[1,2,3]` (n=3)\n    *   Loop: No descents. `descentCount = 0`.\n    *   Wrap-around: `nums[2]` (3) `>` `nums[0]` (1) is `true`. -> `descentCount = 1`.\n    *   Total `descentCount = 1`. Return `true`. Correct. (A sorted array is considered a 0-rotated sorted array).\n\nThis wrap-around check for `nums[n-1] > nums[0]` cleverly handles the case where the \"rotation point\" effectively exists between the last and first element *if the array was originally sorted*. If `[1,2,3]` is seen as `1,2,3,1` (circular), then `3 > 1` is a descent. This means a perfectly sorted array will register 1 descent with this method.\n```\n\n-\n**Final Check:** After iterating through the array and checking the wrap-around, if`descentCount`\n\nis less than or equal to`1`\n\n, it means the array*could have been*sorted and rotated. Return`true`\n\n. Otherwise, if`descentCount`\n\nis greater than`1`\n\n, it means there are too many \"breaks\" in the sorted order for it to be a single rotation of a sorted array. Return`false`\n\n.\n\n### Show Me the Code! 💻\n\nHere's the C++ implementation of this logic:\n\n```\n#include <vector> // Don't forget to include necessary headers!\n#include <iostream> // For potential testing, though not strictly part of the solution\n\nclass Solution {\npublic:\n    bool check(std::vector<int>& nums) {\n        int count = 0; // Initialize descent counter\n        int n = nums.size(); // Get the size of the array\n\n        // Iterate from the second element to compare with the previous\n        for (int i = 1; i < n; i++) {\n            // If the previous element is greater than the current, it's a descent\n            if (nums[i-1] > nums[i]) {\n                count++;\n            }\n        }\n\n        // Handle the wrap-around case: compare the last element with the first\n        // If nums[n-1] is greater than nums[0], it means a \"descent\" occurs\n        // conceptually between the end and the beginning of the array.\n        // E.g., for [1,2,3], nums[2](3) > nums[0](1) is true.\n        // For [3,4,5,1,2], nums[4](2) > nums[0](3) is false.\n        if (nums[n-1] > nums[0]) {\n            count++;\n        }\n\n        // A sorted and rotated array can have at most one \"descent\" (break).\n        // This includes the wrap-around check, meaning a perfectly sorted array\n        // will result in count = 1 due to the wrap-around check.\n        return count <= 1;\n    }\n};\n```\n\n### Complexity Analysis ⏱️🚀\n\nLet `N`\n\nbe the number of elements in the `nums`\n\narray.\n\n-\n**Time Complexity: O(N)**- We iterate through the array once in the\n`for`\n\nloop, which takes`O(N)`\n\ntime. - All other operations (initialization,\n`size()`\n\ncall, final comparison) take constant time,`O(1)`\n\n. - Therefore, the total time complexity is dominated by the loop, making it\n`O(N)`\n\n. This is highly efficient as we only need to pass through the array once.\n\n- We iterate through the array once in the\n-\n**Space Complexity: O(1)**- We only use a few extra variables (\n`count`\n\n,`n`\n\n,`i`\n\n) to store our state, regardless of the input array size. - No auxiliary data structures (like new arrays or hash maps) are used that scale with the input size.\n- Thus, the space complexity is constant,\n`O(1)`\n\n.\n\n- We only use a few extra variables (\n\n### Key Takeaways ✨\n\n-\n**Spotting the \"Breaks\":** The most crucial insight is that a sorted and rotated array will have at most one point where the non-decreasing order is violated. -\n**The Wrap-Around is Tricky:** Don't forget the connection between the last element and the first! This is where many solutions go wrong. Our approach correctly includes this as another potential \"descent.\" -\n**Simple is Often Best:** This problem could tempt you into complex sorting or array manipulation, but a single pass and a counter prove to be the most elegant and efficient solution.\n\nThis approach is clean, efficient, and demonstrates a good understanding of array properties! Keep practicing, and you'll master these patterns in no time. Happy coding!\n\n**Author Account:** Vansh2710\n\n**Time Published:** 2026-05-23 23:46:54", "url": "https://wpnews.pro/news/leetcode-solution-1752-check-if-array-is-sorted-and-rotated", "canonical_source": "https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-1752-check-if-array-is-sorted-and-rotated-996", "published_at": "2026-05-23 18:17:13+00:00", "updated_at": "2026-05-23 18:32:30.423903+00:00", "lang": "en", "topics": [], "entities": ["Vansh2710", "LeetCode"], "alternates": {"html": "https://wpnews.pro/news/leetcode-solution-1752-check-if-array-is-sorted-and-rotated", "markdown": "https://wpnews.pro/news/leetcode-solution-1752-check-if-array-is-sorted-and-rotated.md", "text": "https://wpnews.pro/news/leetcode-solution-1752-check-if-array-is-sorted-and-rotated.txt", "jsonld": "https://wpnews.pro/news/leetcode-solution-1752-check-if-array-is-sorted-and-rotated.jsonld"}}