Parcel-delivery app~12 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1752traversal
A parcel hub publishes its daily departure rota as a list of times, in seconds. A correct rota is in ascending order, and equal times are allowed. A fault in the export may have moved some of the first entries to the end of the list.
Check whether the list is a sorted rota that was rotated by some number of places, including zero places.
Write is_rotated_sorted(times).
times[i] is a departure time, in seconds.true if some rotation of times is in non-decreasing order.false otherwise.Input: times = [30, 40, 50, 10, 20]
Output: trueCount the places where a time is larger than the next one. The last place is compared with the first.
| Place | Time | Next time | Drop? |
|---|---|---|---|
| 0 | 30 | 40 | no |
| 1 | 40 | 50 | no |
| 2 | 50 | 10 | yes |
| 3 | 10 | 20 | no |
| 4 | 20 | 30 | no |
One drop in all, so the list is a rotation of the sorted rota 10, 20, 30, 40, 50.
Input: times = [30, 10, 40, 20]
Output: falseThere are two drops, 30 to 10 and 40 to 20, so no rotation is in order.
Input: times = [5, 5, 5]
Output: trueEqual times never drop, so the list is in order already.
1 ≤ times.length ≤ 100,000 (departures in one rota)0 ≤ times[i] ≤ 1,000,000,000 (seconds)Trying every rotation and checking each one costs about n × n steps, which is 10^10 at n = 100,000. A sorted list that was rotated has one drop at most, and one pass can count the drops, so the work should be about n.