惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
宝玉的分享
宝玉的分享
酷 壳 – CoolShell
酷 壳 – CoolShell
N
Netflix TechBlog - Medium
F
Fortinet All Blogs
T
Tailwind CSS Blog
Google DeepMind News
Google DeepMind News
Jina AI
Jina AI
J
Java Code Geeks
Recent Announcements
Recent Announcements
The Cloudflare Blog
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
Vercel News
Vercel News
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Microsoft Azure Blog
Microsoft Azure Blog
雷峰网
雷峰网
H
Help Net Security
博客园 - Franky
S
SegmentFault 最新的问题
T
The Blog of Author Tim Ferriss
博客园_首页
C
Check Point Blog
腾讯CDC
美团技术团队
Martin Fowler
Martin Fowler
The GitHub Blog
The GitHub Blog
M
MIT News - Artificial intelligence
Apple Machine Learning Research
Apple Machine Learning Research
P
Proofpoint News Feed
U
Unit 42
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Engineering at Meta
Engineering at Meta
M
Microsoft Research Blog - Microsoft Research
阮一峰的网络日志
阮一峰的网络日志
G
Google Developers Blog
Stack Overflow Blog
Stack Overflow Blog
B
Blog
Last Week in AI
Last Week in AI
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
云风的 BLOG
云风的 BLOG
H
Hackread – Cybersecurity News, Data Breaches, AI and More
李成银的技术随笔
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 叶小钗
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

DEV Community

Optic is dead. A 2026 migration guide for OpenAPI breaking changes Smart Blind Stick, Mini Project The NSA just published an MCP security playbook. We created Agent Trust Transport Protocol ATTP - Implement today with MCPS Symfony 8 AWS Secrets Bundle What RepoSignal Surfaced in React — and Why Review Alone Doesn't Catch Everything Breaking the Matrix at 15: How I Built a Cyber-Aesthetic AI Assistant Core Powered by Gemma 4 Разработка Android Kiosk приложения No More Manual Test Writing: How I Used Gemma 4 to Turn a GitHub Repo Into a Full Test Suite 🎯 Trafik Cezaları Platformları Geliştirirken Öğrendiğim Teknik Dersler The Myth of Low Latency: Why Event Meshes Make Your System Slow Building EIDOLON OS — A Local-First AI Cognitive Operating System qrrot - database with AI I Built a Local Gemma 4 Reviewer for Merchant Registry Evidence Compass v1.1.0 · we shipped a memory plugin that catches its own consumption drift How to build your first MCP server in 10 minutes Expo SDK 56 Is Out, and a Few Things Finally Clicked Into Place Building a 100ms Browser-Native WebSocket Clipboard Cómo solucionar `docker run` con `Exited (1)` en Raspberry Pi Why Claude Code Sessions Diverge: A Mechanism Catalog When One AI Agent Is Not Enough: A Practical Delegation Pattern for Enterprise Systems Cómo solucionar el bucle infinito en `useEffect` con objetos y arrays 🛢️ The Dangote Chain: What a Blockchain-Native Refinery IPO Would Look Like Build a "Where to Watch" feature in 50 lines with the StreamWatchHub API Gemma 4 on Android: Tricks for Faster On-Device Inference Your AI agent has amnesia. You've just normalized it. 🚀 Reviving My Women Safety System – From Idea to Real-Time Smart Safety Solution I built an AI that reviews every PR automatically (because nobody was reviewing mine) 🌿 Git Mastery: The Complete Developer Guide Bringing Gemma 4 E2B to the Edge: Building a Privacy-First Dream Analyzer with Flutter & LiteRT Google I/O 2026 Wasn’t About Features — It Was About AI Becoming the Developer Environment Building an AI Vedic Astrology App in 25 Days — What Actually Worked (and What Didn't) Hermes Agent Has Four Memories — And That's Why It Doesn't Forget You Pressure Isn't Killing You -Your Relationship With It Is 🐳 How to Run Any Project in Docker: A Complete Guide AccessLens — a blind person's lanyard, powered by Gemma 4 on-device Glyph v0.2: the release is the joinery How I Built a Blazingly Fast, Privacy-First Batch Image Converter in the Browser Using OPFS and Web Workers Cómo solucionar \"Text content does not match server-rendered HTML\" en Next.js App Router FCoP 3.0: Why AI Agents Need a Track, Not a Brake Fibonacci: Quiz app which anyone can make revenue by viewing ads to the quiz contestants. The Subconscious Powered by Edge AI GPU Utilization Is Becoming the New Cloud Waste Crisis Cómo solucionar `docker run` con exit code 1 en Raspberry Pi JWT is a scam and your app doesn't need it 7 Agent Skill Packs That Actually Make AI Coders Better More Control, More Cost: Why Commanding AI Isn't Delegation SecureScan Synthadoc: We Built an AI Judge for Our AI Wiki Compiler - Here's What We Learned Cómo solucionar el error de permiso al ejecutar `pip.exe` en entorno virtual (Python 3.10 en Windows) Postgres-grade Serializable at 20k+ ops/s — on a laptop. Don’t try this at home. Pure Core, Imperative Shell in Rust with Stillwater Lean 4 for Programmers: Building a Todo List with Proof Trustless Bug Bounty Releases with a PoW-Gated DLC Oracle Building Autonomous DevOps Agents with MCP and LangChain Multimodal Gemma 4 Visual Regression & Patch Agent Git Time Machine — How Version Control Can Save Your Project My Dad Got an Electricity Bill He Couldn't Understand. Google I/O 2026 Just Made That Problem Solvable. My Dad Got an Electricity Bill He Couldn't Understand. Google I/O 2026 Just Made That Problem Solvable. Read Replicas Lie About Consistency. 4 Sync Modes Behind the Lie. Reviving My Coding Project with GitHub Copilot I Tried Gemini 3.5 Flash After Google I/O 2026 - Here is What I Found :)) Zero-Cost AI in VS Code Blueprints Might Be More Important Than Frameworks AI CareCompanion - Offline Health Assistant Long-Context Models Killed RAG. Except for the 6 Cases Where They Made It Worse. I Built a Neural Network Engine in C# That Runs in Your Browser - No ONNX Runtime, No JavaScript Bridge, No Native Binaries An In-Depth Overview of the Apache Iceberg 1.11.0 Release Your Agent Just Called the Same Tool 47 Times. Here's the 20-Line Detector. How I Built a Multi-System Astrology Bot in Python (And What Meta Banned Me For) Gemma 4 Has Four Variants. Here's How to Pick the Right One Before You Write a Single Line of Code. Log Level Strategies: Balancing Observability and Cost Why WebMCP Is the Most Important Thing Google Announced at I/O 2026 (And Nobody's Talking About It) Making LLM Calls Reliable: Retry, Semaphore, Cache, and Batch Google's 2x Energy Efficiency Claim Is Real — But Here's What They're Not Measuring What's actually going on with CORS, under the hood Language-Agnostic Code Generation: The Driver Plugin Model Why We Rewrote Our Python CLI in Go (and What We Gained) I added up everything Google gives developers for free after I/O 2026. It's kind of absurd The Dawn of Smarter Apps: My Take on Google I/O 2026 AI Announcements Why AI Agents Like Hermes Need a Semantic Execution Layer for the Physical World Why We Built TestSmith: The Test Coverage Problem Nobody Talks About How to Convert Bank Statement PDFs to Excel: The Complete 2026 Guide Have You Ever Used a Website That Keeps Working After You Turn Off Your Internet? From idea to indexed: how I launched a SaaS in 60 days with Laravel + React Building a local-first AI tutor for my daughter (and 10–14 year-olds in Austrian schools) with Gemma 4 EC2 SSH Not Connecting? Here Are the 5 Things That Were Wrong (And How I Fixed Them) Best AI Tools for HVAC Contractors 2026 From Closed Internal Stack to Open-Source Ecosystem: I Finally Shipped Three Years of .NET Infrastructure Scrumpan is offlically LIVE!! Building a BMI Calculator CLI with TypeScript — Types, Functions, and Vitest From Building WordPress Websites to Node.js APIs: My Honest Full Stack Journey XiHan Snore Coach: Privacy-First On-Device MedTech Guardian powered by Gemma 4 Mobile Why AI Coding Agents Hallucinate and How to Fix It mcp-probe v1.4.0: Contract assertions for production MCP servers Google I/O 2026 Wasn't About One More Model. It Was About the Agent Stack. How I built 100+ crypto calculators in 6 languages on Astro The Dawn of Local Multi-Agent Architectures: Why Gemma 4 Changes Everything for Cloud Developers # I Told My AI to Simulate a Planet for 10,000 Years. It Built the Whole Thing Itself. 18/30 Days System Design Questions! From Hackathon Chaos to Clean CLI: Reviving My Daily Routine Analyser with GitHub Copilot
LeetCode Solution: 1752. Check if Array Is Sorted and Rotated
Vansh Aggarw · 2026-05-24 · via DEV Community

🔄 LeetCode 1752: Can You Un-Rotate This Array? (A Beginner's Guide)

Hey 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!

This 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!


What's the Problem All About? 🧐

Imagine you have a perfectly sorted list of numbers, like [1, 2, 3, 4, 5].
Now, imagine you rotate it. This means you take some elements from the beginning and move them to the end, keeping their relative order.

For example, if you rotate [1, 2, 3, 4, 5] by 2 positions:

  1. [1, 2, 3, 4, 5]
  2. Take 1, 2 and move them to the end: [3, 4, 5, 1, 2]

The 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)?

Key things to remember:

  • Non-decreasing order: [1, 2, 2, 3] is sorted. [3, 2, 1] is not.
  • Rotation: Can be any number of positions, including 0 (no rotation).
  • Duplicates are allowed: This is an important detail! [3, 4, 5, 5, 1, 2] could be [1, 2, 3, 4, 5, 5] rotated.

Let's look at examples:

  • nums = [3, 4, 5, 1, 2]

    • Is [1, 2, 3, 4, 5] sorted? Yes.
    • Can [1, 2, 3, 4, 5] be rotated to get [3, 4, 5, 1, 2]? Yes, rotate by 2 positions.
    • Output: true
  • nums = [2, 1, 3, 4]

    • If sorted, it would be [1, 2, 3, 4].
    • Can [1, 2, 3, 4] be rotated to [2, 1, 3, 4]? No. The 2, 1 part breaks the sorted order that a single rotation would maintain.
    • Output: false
  • nums = [1, 2, 3]

    • Is it sorted? Yes.
    • Can it be rotated to get [1, 2, 3]? Yes, 0 rotations.
    • Output: true

The "Aha!" Moment - Our Intuition ✨

Think about a truly sorted array like [1, 2, 3, 4, 5]. If you go from left to right, nums[i-1] is always less than or equal to nums[i]. There are no "drops" or "descents" in value.

Now, consider a rotated sorted array: [3, 4, 5, 1, 2].
If you scan this, you'll see:

  • 3 <= 4 (OK)
  • 4 <= 5 (OK)
  • 5 > 1 (AHA! A descent!)
  • 1 <= 2 (OK)

Notice something? There's only one place where the non-decreasing order is broken: 5 followed by 1. This "break" is exactly where the rotation happened! The elements [1, 2] were moved from the beginning to the end, creating this single drop in value.

What if there are two descents? For example, [2, 1, 3, 4].

  • 2 > 1 (Descent 1)
  • 1 <= 3 (OK)
  • 3 <= 4 (OK) Here, we have one descent. What about the wrap-around? 4 > 2? No. Actually, if the original array was [1,2,3,4], and we rotated it, we would never get [2,1,3,4]. 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.

So, 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.

Wait, what about the wrap-around?
Consider [4, 5, 1, 2, 3].
4 <= 5 (OK)
5 > 1 (Descent!)
1 <= 2 (OK)
2 <= 3 (OK)
Here, we have one descent. But also, nums[n-1] (which is 3) is less than nums[0] (which is 4). This comparison also forms part of the "break" in sorted order, conceptually wrapping around the array. Our descent counter needs to account for this.

Revised Intuition: Count the number of times nums[i-1] > nums[i]. This count should be at most 1, including the wrap-around comparison between the last and first elements.


Step-by-Step Approach 🚶‍♂️

Let's formalize our intuition into a clear algorithm:

  1. Initialize a counter: We'll need a variable, let's call it descentCount, and set it to 0. This counter will track how many times we find nums[i-1] > nums[i].

  2. Iterate through the array: Loop from the second element (i = 1) up to the end of the array (nums.size() - 1).

    • In each iteration, compare the current element (nums[i]) with the previous one (nums[i-1]).
    • If nums[i-1] > nums[i], it means we've found a "descent" or a break in the non-decreasing order. Increment descentCount.
  3. 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], nums[4] (which is 2) is less than nums[0] (which is 3). This doesn't add a descent.
    However, in [1,2,3] (0 rotations), nums[2] (3) is greater than nums[0] (1).
    Let's re-evaluate: The descent is where the sequence decreases.

    • [3, 4, 5, 1, 2] -> 5 > 1 (1 descent)
      • nums[n-1] (2) is not greater than nums[0] (3).
    • [1, 2, 3] -> No descents.
      • nums[n-1] (3) is not greater than nums[0] (1).
    • [2, 1, 3, 4] -> 2 > 1 (1 descent)
      • nums[n-1] (4) is not greater than nums[0] (2).

    My logic for the wrap-around check in the solution code is if (nums[n-1] > nums[0]). Let's trace it with examples:

    • [3,4,5,1,2] (n=5)
      • Loop: (5 > 1) -> descentCount = 1
      • Wrap-around: nums[4] (2) > nums[0] (3) is false.
      • Total descentCount = 1. Return true. Correct.
*   `[2,1,3,4]` (n=4)
    *   Loop: `(2 > 1)` -> `descentCount = 1`
    *   Wrap-around: `nums[3]` (4) `>` `nums[0]` (2) is `true`. -> `descentCount = 2`.
    *   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)).

*   `[1,2,3]` (n=3)
    *   Loop: No descents. `descentCount = 0`.
    *   Wrap-around: `nums[2]` (3) `>` `nums[0]` (1) is `true`. -> `descentCount = 1`.
    *   Total `descentCount = 1`. Return `true`. Correct. (A sorted array is considered a 0-rotated sorted array).

This 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.

Enter fullscreen mode Exit fullscreen mode

  1. Final Check: After iterating through the array and checking the wrap-around, if descentCount is less than or equal to 1, it means the array could have been sorted and rotated. Return true. Otherwise, if descentCount is greater than 1, it means there are too many "breaks" in the sorted order for it to be a single rotation of a sorted array. Return false.

Show Me the Code! 💻

Here's the C++ implementation of this logic:

#include <vector> // Don't forget to include necessary headers!
#include <iostream> // For potential testing, though not strictly part of the solution

class Solution {
public:
    bool check(std::vector<int>& nums) {
        int count = 0; // Initialize descent counter
        int n = nums.size(); // Get the size of the array

        // Iterate from the second element to compare with the previous
        for (int i = 1; i < n; i++) {
            // If the previous element is greater than the current, it's a descent
            if (nums[i-1] > nums[i]) {
                count++;
            }
        }

        // Handle the wrap-around case: compare the last element with the first
        // If nums[n-1] is greater than nums[0], it means a "descent" occurs
        // conceptually between the end and the beginning of the array.
        // E.g., for [1,2,3], nums[2](3) > nums[0](1) is true.
        // For [3,4,5,1,2], nums[4](2) > nums[0](3) is false.
        if (nums[n-1] > nums[0]) {
            count++;
        }

        // A sorted and rotated array can have at most one "descent" (break).
        // This includes the wrap-around check, meaning a perfectly sorted array
        // will result in count = 1 due to the wrap-around check.
        return count <= 1;
    }
};

Enter fullscreen mode Exit fullscreen mode


Complexity Analysis ⏱️🚀

Let N be the number of elements in the nums array.

  • Time Complexity: O(N)

    • We iterate through the array once in the for loop, which takes O(N) time.
    • All other operations (initialization, size() call, final comparison) take constant time, O(1).
    • Therefore, the total time complexity is dominated by the loop, making it O(N). This is highly efficient as we only need to pass through the array once.
  • Space Complexity: O(1)

    • We only use a few extra variables (count, n, i) 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.
    • Thus, the space complexity is constant, O(1).

Key Takeaways ✨

  • 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.
  • 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."
  • 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.

This 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!


Author Account: Vansh2710
Time Published: 2026-05-23 23:46:54