Online store~15 min2s · 256 MBtarget O(q log^2 n) time, O(log n) spacerecursion
An online store gives every order a number: 1, 2, 3 and so on, with no gaps. A support tool checks a report by adding the digits of every order id from 1 up to the latest one.
Adding the digits of one id is a small recursion. Take the last digit, then add the digits of everything before it. The recursion stops when no digits are left.
Write digit_totals(last_ids).
last in last_ids, return the sum of the digit sums of every id from 1 to last, both included.last can be 10^12.Input: last_ids = [25]
Output: [127]Take last = 25. Group the ids by the prefix before the last digit.
| Ids | Prefix | Digit total |
|---|---|---|
| 1 to 9 | none | 45 |
| 10 to 19 | 1 | 55 |
| 20 to 25 | 2 | 27 |
Ten ids share the prefix 1, so the prefix adds 1 × 10 and the last digits add 45. The six ids 20 to 25 add 2 × 6 + (0 + 1 + 2 + 3 + 4 + 5). The total is 45 + 55 + 27 = 127.
Input: last_ids = [9, 1]
Output: [45, 1]The ids 1 to 9 have the digit total 1 + 2 + ... + 9 = 45, and the id 1 alone has the total 1.
Input: last_ids = [100, 7, 99]
Output: [901, 28, 900]The ids 1 to 100 total 901. The ids 1 to 7 total 28, and the ids 1 to 99 total 900. The id 100 adds 1.
1 ≤ last_ids.length ≤ 1,0001 ≤ last_ids[i] ≤ 1,000,000,000,000The length bound of 1,000 is small, and the ids are large. One last of 10^12 means a trillion ids, so the work must depend on the number of digits, which is 13. A recursion that removes one digit at a time is at most 13 frames deep.