Given a one-dimensional integer array nums of length n, visit its indices in the alternating order 0, n - 1, 1, n - 2, 2, n - 3, ... until every index has been visited exactly once. When n is odd, the center index is visited exactly once, as the last element.
Return True if the sequence of visited values is nondecreasing, and False otherwise.
You must not sort or modify nums.
Function Signature
def is_spirally_sorted(nums: list[int]) -> bool:
...
Rules
-
The visit order takes the next unvisited index from the left end, then from the right end, and keeps alternating, starting with the left end.
-
Nondecreasing means each visited value is greater than or equal to the value visited just before it, so equal neighbors are allowed.
-
An array with one element is always nondecreasing.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [2,6,8,4]
Output: True
The visit order of indices is 0, 3, 1, 2, which gives the values 2, 4, 6, 8. That sequence is nondecreasing.
Input: nums = [2,4,8,6]
Output: False
The visit order of indices is 0, 3, 1, 2, which gives the values 2, 6, 4, 8. Since 6 > 4, the sequence is not nondecreasing.
Input: nums = [1,4,9,4,1]
Output: True
The visit order of indices is 0, 4, 1, 3, 2, which gives the values 1, 1, 4, 4, 9. Equal neighbors are allowed, and the center index 2 comes last.