1322. Digit Pass Snapshot

Easy1.5 points estimatedRadix SortSortingArray

A depot sorts parcel codes with a classic digit sort and wants to inspect the order after only a few rounds. The array nums holds non-negative integers. One round is a stable counting sort on a single decimal digit: round 1 looks at the units digit, round 2 at the tens digit, round 3 at the hundreds digit, and so on, always starting from the order left by the previous round. Elements with the same digit keep the relative order they had before the round. A digit that does not exist counts as 0.

Given nums and passes, return the array exactly as it stands after passes rounds. With 0 rounds the array is unchanged. Equivalently, the result is a stable sort of nums by the value of nums[i] modulo 10^passes. Aim for O(passes * (n + 10)) time and O(n) extra space.

Example 1

Input:
nums = [512,38,907,244,61,700], passes = 1
Output:
[700,61,512,244,907,38]
Explanation:

The units digits are 2, 8, 7, 4, 1, 0, so one round orders the values by them: 700, 61, 512, 244, 907, 38.

Example 2

Input:
nums = [512,38,907,244,61,700], passes = 2
Output:
[700,907,512,38,244,61]
Explanation:

Starting from the order after round 1, the tens digits are 0, 6, 1, 4, 0, 3; a stable round gives 700, 907, 512, 38, 244, 61.

Example 3

Input:
nums = [512,38,907,244,61,700], passes = 3
Output:
[38,61,244,512,700,907]
Explanation:

The hundreds digits of the previous order are 7, 9, 5, 0, 2, 0, so a third round finishes the sort: 38, 61, 244, 512, 700, 907.

Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ nums[i] ≤ 109
  • 0 ≤ passes ≤ 10

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(passes * (n + 10))
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…