Add One to Digit Array
Company: Intuit
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in array manipulation and elementary arithmetic on digit sequences, specifically carrying operations and edge-case handling for overflow.
Part 1: Add One to a Digit Array
Constraints
- 0 <= len(digits) <= 1000000
- Each element of digits is an integer between 0 and 9.
- digits has no leading zeros unless digits == [0].
- An empty list represents 0.
- Do not convert the entire digit array to a built-in integer.
Examples
Input: ([1, 2, 3],)
Expected Output: [1, 2, 4]
Explanation: 123 + 1 = 124.
Input: ([1, 2, 9],)
Expected Output: [1, 3, 0]
Explanation: The final 9 becomes 0 and carries 1 to the 2.
Input: ([9, 9, 9],)
Expected Output: [1, 0, 0, 0]
Explanation: All digits carry, so the result needs one extra digit.
Input: ([0],)
Expected Output: [1]
Explanation: The number 0 plus 1 is 1.
Input: ([],)
Expected Output: [1]
Explanation: By problem definition, an empty digit array represents 0.
Hints
- Addition by 1 only affects digits starting from the least significant digit.
- A digit 9 becomes 0 and passes a carry to the digit on its left.
Part 2: Add One to a Huge Chunked Digit Stream
Constraints
- 0 <= len(chunks) <= 1000000
- Each chunk is a non-empty string of decimal digits, except that chunks may be empty to represent 0.
- Chunks are ordered from least significant to most significant.
- All chunks except the most significant chunk have the same width.
- Lower chunks may contain leading zeros; the most significant chunk has no leading zeros unless the number is exactly 0.
- Do not concatenate all chunks or convert the entire number to a built-in integer.
Examples
Input: (['789', '456', '123'],)
Expected Output: ['790', '456', '123']
Explanation: The chunks represent 123456789. Adding 1 only changes the least significant chunk.
Input: (['999', '129'],)
Expected Output: ['000', '130']
Explanation: The chunks represent 129999. The lower chunk overflows from 999 to 000 and carries into 129.
Input: (['999', '999'],)
Expected Output: ['000', '000', '1']
Explanation: 999999 + 1 = 1000000, requiring a new most significant chunk.
Input: (['009', '1'],)
Expected Output: ['010', '1']
Explanation: The chunks represent 1009. The lower chunk keeps its fixed width after incrementing.
Input: ([],)
Expected Output: ['1']
Explanation: By problem definition, an empty chunk list represents 0.
Hints
- The carry from adding 1 moves from the least significant side toward the most significant side.
- A chunk made entirely of 9s becomes all 0s and keeps the carry; otherwise, increment the rightmost non-9 digit in that chunk and stop carrying.