← DiffPush

Check if array is sorted and rotated

Baseline Arrays · Easy O(n) · O(1)

Integrity Check on a Circular Log Buffer

A metrics collector keeps its timestamps in a circular buffer, so the stored sequence may look shifted after a restart. Before serving queries, the collector must prove the readings would read as non-decreasing if the ring were unrolled at the right point. Determine whether the buffer was originally sorted and then rotated by some number of positions, including zero.

Input: An array nums of n integers representing the buffer contents.

Output: true if nums can be obtained by rotating a non-decreasing array, otherwise false.

Constraints

Examples

Example 1

Input: {"nums":[3,4,5,1,2]}
Output: true
Unrolling the ring after 5 gives 1,2,3,4,5, which is non-decreasing, so the buffer is a rotation of a sorted sequence.

Example 2

Input: {"nums":[2,1,3,4]}
Output: false
No rotation of a non-decreasing sequence drops once and then rises again in the middle, so the answer is false.

Solve this in your browser →

Also on LeetCode ↗