Ride-hailing app~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-66traversal
A ride-hailing app numbers every trip receipt. The numbers grow for years, so the app stores each one as a list of decimal digits, with the most significant digit first. No integer type is big enough.
When a trip ends, the app prints the next receipt, which is the stored number plus one. Your team lead asks you to write that step on the digits themselves.
Write next_receipt(digits).
digits holds the digits of a non-negative number, most significant first. The first digit is never 0, unless the number is 0 itself and digits is [0].0.Input: digits = [1, 2, 9]
Output: [1, 3, 0]The number is 129, and the next one is 130. Start at the last digit. A 9 plus one is ten, so it becomes 0 and a carry moves left.
The next digit is 2, and 2 plus the carry is 3. The carry stops there.
| Step | Digit | Action | Digits now |
|---|---|---|---|
| [1] | start | copy the digits | [1, 2, 9] |
| [2] | 9 |
becomes 0, carry left |
[1, 2, 0] |
| [3] | 2 |
not a 9, so add one |
[1, 3, 0] |
Input: digits = [9, 9]
Output: [1, 0, 0]Both digits are 9. They become 0, and the carry has nowhere to go, so a new first digit 1 is added.
Input: digits = [4, 3, 2, 1]
Output: [4, 3, 2, 2]The last digit is not 9, so it grows by one and nothing else changes.
1 ≤ length of digits ≤ 10000000 to 90, unless digits is [0]A number of 1,000,000 digits does not fit any integer type, so the arithmetic must happen on the digits. The carry moves one digit to the left at a time, and it stops at the first digit that is not a 9.
Building the answer by inserting each new digit at the front moves every digit already there, and that costs about 1,000,000 × 1,000,000 ÷ 2 moves. Change the digits in place, and build the longer answer only when every digit is a 9.