Maps app~20 min2s · 256 MBtarget O(passes × n) time, O(n) spacesorting
A maps app stores each map tile under a six-digit code. A batch job sorts the codes with a radix sort: one stable counting pass for each digit, from the last digit to the first.
A pass sorts the codes by one digit only, and codes with the same digit stay in the order the previous pass left them. Your team lead wants to see the list after a chosen number of passes, to check that the job stops where it should.
Write radix_after_passes(codes, passes).
passes passes. When passes is 0, return the codes in their input order.Input: codes = [329, 457, 657, 839, 436, 720, 355], passes = 2
Output: [720, 329, 436, 839, 355, 457, 657]Pass 1 sorts by the last digit. Pass 2 sorts by the tens digit and keeps ties in the order of pass 1.
| After | Codes |
|---|---|
| Input | 329, 457, 657, 839, 436, 720, 355 |
| Pass 1 | 720, 355, 436, 457, 657, 329, 839 |
| Pass 2 | 720, 329, 436, 839, 355, 457, 657 |
Codes 720 and 329 both have the tens digit 2. Code 720 was first after pass 1, so it stays first.
Input: codes = [21, 12], passes = 1
Output: [21, 12]One pass sorts by the last digit only: 21 ends in 1 and 12 ends in 2.
Input: codes = [12, 15, 11, 10], passes = 2
Output: [10, 11, 12, 15]The second digit is 1 for all four codes. They keep the order of pass 1: 10, 11, 12, 15.
0 ≤ codes.length ≤ 100,000 (tiles)0 ≤ codes[i] ≤ 999,999 (six-digit code)0 ≤ passes ≤ 6Sorting by the last passes digits with insertion costs about n × n / 4 shifts, which is 2,499,975,000 at n = 100,000. A stable counting pass costs 2n + 10 steps, so six passes cost about 1.2 million steps.