1324. Passes Until Sorted
A warehouse runs a digit-by-digit sorting machine on stock numbers and wants to know how long it must run. The array nums holds non-negative integers. Pass p (for p = 1, 2, 3, ...) stable-sorts the whole current array by the p-th digit counted from the right, where the units digit is the first digit and a missing digit counts as 0. Every pass starts from the order produced by the previous pass, and elements with equal digits keep their relative order.
Return the smallest p >= 0 such that the array is in non-decreasing order after exactly p passes. Return 0 if nums is already non-decreasing. Simulate the passes one at a time and check the order after each one; no more than 10 passes are ever needed. Expected cost is O(10 * n) time and O(n) space.
Example 1
- Input:
- nums = [42,17,93,8]
- Output:
- 2
- Explanation:
After pass 1 (units) the order is 42, 93, 17, 8, still unsorted; after pass 2 (tens) it is 8, 17, 42, 93, so the answer is 2.
Example 2
- Input:
- nums = [5,6,7]
- Output:
- 0
- Explanation:
The array is already non-decreasing, so no pass is needed.
Example 3
- Input:
- nums = [31,21,11,1]
- Output:
- 2
- Explanation:
All units digits are 1, so pass 1 changes nothing; pass 2 orders by the tens digits 3, 2, 1, 0 and yields 1, 11, 21, 31.
Constraints
- 1 ≤ n ≤ 1000
- 0 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(10 * n)
- Space
- O(n)