1502. Clock Dial Sorting
A workshop has a row of n circular dials. Dial i currently shows the value a[i] on a face numbered 0 to m - 1. In one operation you choose any set of dials (possibly none) and turn each chosen dial forward by exactly one notch, so a shown value v becomes (v + 1) % m.
The dials are in order when the shown values, read left to right, are non-decreasing. Return the minimum number of operations needed to get there. Note that no single dial ever needs more turns than the number of operations, so the answer is the smallest budget x such that every dial can be turned at most x times and the row ends up sorted. This budget is monotone, so it can be searched, and a left-to-right greedy that keeps each value as small as allowed decides a budget. Aim for O(n log m) time and O(1) extra space.
Example 1
- Input:
- a = [3,1,4,1,5], m = 6
- Output:
- 3
- Explanation:
Three operations turn both 1s into 4s (3,4,4,4,5), and with only two turns the second dial cannot reach 3 or more while the fourth stays valid.
Example 2
- Input:
- a = [0,0,0], m = 5
- Output:
- 0
- Explanation:
The row is already non-decreasing, so no operation is needed.
Example 3
- Input:
- a = [4,0], m = 5
- Output:
- 1
- Explanation:
One operation turns the first dial from 4 to 0, giving 0,0.
Constraints
1 ≤ n ≤ 105
1 ≤ m ≤ 105
0 ≤ a[i] < m
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log m)
- Space
- O(1)