⚡Flashcard Drill➔
NeetCode #63LC-1752EasyArrays & Hashing
← Back to All Problems

#63 · #1752 · Check if Array Is Sorted and Rotated(检查数组是否经排序和轮转得到)

📌 Problem Statement & Constraints

Given an array nums, return true if it was originally sorted in non-decreasing order and then rotated some number of positions (including zero). Constraints: 1 <= nums.length <= 100, 1 <= nums[i] <= 100.

💡 Core Algorithmic Approaches

  1. A rotation of a sorted array has at most one descent, where nums[i] > nums[i + 1].
  2. Count descents across the array, treating it as circular by also comparing the last element with the first.
  3. If the total number of descents is at most 1, the array is a valid rotation.
  4. The circular comparison is the part candidates miss: [2, 1, 3, 4] has one linear descent but the wrap-around also descends, giving two, so it is not a rotation.

💻 Benchmark Python3 Implementation

class Solution:
    def check(self, nums: List[int]) -> bool:
        n = len(nums)
        descents = 0
        for i in range(n):
            if nums[i] > nums[(i + 1) % n]:    # circular comparison
                descents += 1
        return descents <= 1

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): a single counter.

⚠️ Interview Pitfalls & Follow-ups

  • Only scanning 0..n-2: the wrap-around comparison from the last element back to the first is required to detect arrays like [2, 1, 3, 4].
  • Requiring exactly one descent: a fully sorted array has zero descents and is a valid rotation (by zero positions).
  • Using >=: duplicates are allowed, so equal neighbours are not descents. The comparison must be strict.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

检查数组是否经排序和轮转得到

给你一个数组 nums。nums 的源数组中,所有元素与 nums 相同,但按非递减顺序排列。如果 nums 能够由源数组轮转(可轮转 0 次或多次)得到,返回 true;否则返回 false。源数组中可能存在 重复 元素。约束:1 ≤ nums.length ≤ 100;1 ≤ nums[i] ≤ 100。

核心要点

  • 统计「下降点」个数(标准解) :在一个非递减的循环数组中,相邻元素发生下降( nums[i] &gt; nums[i+1] )的位置最多只能有 1 个。
  • 为什么是 1 个 :轮转把原数组切成两段,断裂处最多产生一个下降点。若下降点 ≥ 2,说明有两处断裂,无法由单次轮转得到。
  • 环形比较 :遍历 i 从 0 到 n-1,比较 nums[i] 与 nums[(i+1) % n] ,统计下降次数。
  • 重复元素的处理 :本题允许重复,但下降点的判定依然成立——相等不算下降,因此不影响结论。

常见陷阱

  • 忘记取模构成环形 :只比较 nums[i] &gt; nums[i+1] (不包含 nums[n-1] 与 nums[0] )会漏掉断裂处恰好位于首尾之间的情况。
  • 把条件写成 drops == 1 :原数组本身就是非递减(轮转 0 次)时下降点为 0,也应返回 True,因此必须是 &lt;= 1 。
  • 试图真正做轮转再比较 :枚举 n 种轮转再逐一比较是 O(n²),而且实现更复杂。下降点计数是 O(n) 的最优解。

参考实现

class Solution:
    def check(self, nums: list[int]) -> bool:
        n = len(nums)
        drops = sum(1 for i in range(n) if nums[i] > nums[(i + 1) % n])
        return drops <= 1