15% off all plans & roadmaps Use code
See plansAdd to Array-Form of Integer
- LeetCode 989
- Easy
- Array/Matrix Manipulation Patterns
- Plus One (Handling Carry)
Updated
TL;DR: You add k to a number stored one digit per array slot. Walk from the last digit to the first, keep k's remaining value as a carry, and prepend any leftover digits.
Problem
An array-form integer stores its decimal digits in an array, read from the most significant digit on the left to the least significant digit on the right. For example, the integer 1321 is stored as [1,3,2,1].
You receive an array-form integer num and a plain integer k. Return the array-form of the sum num + k.
Example 1
Input: num = [1,2,0,0], k = 34 Output: [1,2,3,4] Explanation: 1200 + 34 = 1234
Example 2
Input: num = [2,7,4], k = 181 Output: [4,5,5] Explanation: 274 + 181 = 455
Example 3
Input: num = [2,1,5], k = 806 Output: [1,0,2,1] Explanation: 215 + 806 = 1021
Example 4
Input: num = [9,9,9,9,9,9,9,9,9,9], k = 1 Output: [1,0,0,0,0,0,0,0,0,0,0] Explanation: 9999999999 + 1 = 10000000000
Constraints
1 <= num.length <= 10^40 <= num[i] <= 9numhas no leading zeros, except the number zero itself.1 <= k <= 10^4
Constraints that matter
- num can have 10^4 digits, which is far beyond any fixed-width integer type. That rules out converting num to a number and adding k.
- k is at most 10^4, so it has at most five digits and fits easily in an int or long. Its digits only reach a few columns past the end of num.
- Incrementing by one k times costs up to about 10^8 digit steps in the worst case. A solution that walks num once is the target.
- Every output digit comes from one column, so the answer has at most about n + 10 digits. Any approach that touches each column a constant number of times is fast enough.
Hints
Hint 1
The array is a base-10 number, and k is another base-10 number.
Hint 2
Start from num and add 1 to it, k times.
Solution
Intuition
The array is a base-10 number, and k is another base-10 number. Adding them is the column addition you learned in school. The work starts at the last digit and moves left, because a carry always moves in that direction.
It is like adding two numbers on paper, one column at a time. Each array slot is a column, and the carry is the small number you write above the next column to the left.
Each column produces one output digit and one carry. You do not need to split k into digits first. Keep k whole as the carry, add the current digit of num to it, write the ones place, and divide the rest by ten. That division pushes the tens part into the next column.
This is the carry propagation pattern, the same idea used in Plus One. Once num runs out, the carry still holds digits, so you keep writing them. The digits come out in reverse order, so you reverse the result at the end.
Worked example
Input: num = [1, 0, 0, 0], k = 9999 Output: [1, 0, 9, 9, 9] Explanation: The number 1000 plus 9999 is 10999. The carry shrinks by a factor of ten at each column, so the trace has five columns: four from num and one more from the leftover carry.
Approach 1: Brute force: increment k times
Start from num and add 1 to it, k times. Each +1 walks from the last digit, turns trailing 9s into 0s, and adds 1 to the first digit that is not 9. If every digit is 9, it inserts a 1 at the front. This is the naive version a beginner writes, because it repeats the same increment rule for every unit of k.
The obvious alternative is to build a machine integer from num, add k, and convert back. That fails for 10^4 digits in C++, Java, Go, JavaScript and C#, so it is not a valid answer here.
Steps
- Copy the digits of num into a working list so the input stays unchanged.
- Repeat k times: set i to the last index of the list.
- While i is valid and the digit at i is 9, set it to 0 and move i one step left.
- If i is still valid, add 1 to the digit at i. Otherwise insert a 1 at the front of the list.
- Return the list after the k increments.
Dry run
Start with [1,0,0,0] and k = 9999. The first increment gives [1,0,0,1]. The second gives [1,0,0,2], and after nine increments the array is [1,0,0,9].
The tenth increment turns the trailing 9 into 0, then adds 1 to the zero before it, which gives [1,0,1,0]. Every block of ten increments adds one to the tens digit. After all 9999 increments the array is [1,0,9,9,9], which matches the expected output.
Complexity
| Time | O(k * n) |
|---|---|
| Space | O(n) |
Let n be the length of num. One increment scans from the right until it finds a digit that is not 9, which takes at most n steps, and the rare insert at the front also costs O(n). The loop runs k times, so the worst case is O(k * n), reached when every increment carries through all digits. The working copy uses O(n) extra space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
digits = list(num) # copy so the input is not changed
for _ in range(k):
i = len(digits) - 1
# Turn trailing 9s into 0s while carrying left
while i >= 0 and digits[i] == 9:
digits[i] = 0
i -= 1
if i >= 0:
digits[i] += 1
else:
digits.insert(0, 1) # every digit was 9
return digitsThe Plus One (Handling Carry) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Plus One (Handling Carry)
Approach 2: One-pass carry from the rightOptimalPlus One (Handling Carry)
The brute force repeats work. Each +1 rescans the same trailing 9s, and it treats k as k separate ones. What's slow is that the carry from earlier columns is recomputed from scratch each time.
The insight that fixes it is to keep k whole as the carry. At each column, add num's digit to the carry, write the carry mod 10 as the output digit, and divide the carry by 10 for the next column. Each column is handled exactly once, and the carry shrinks by a factor of ten once num is used up.
Digits come out least significant first. Append them to a list and reverse once at the end, because inserting at the front costs O(n) each time.
Why it is correct. Each column has no free choice, so its output digit is forced by the digit from num plus the incoming carry. The carry is exactly the amount that spills into the next place value, so no value is lost or counted twice. When num runs out, the leftover carry is written in full, so the result equals the true sum.
Steps
- Set i to the last index of num and carry to k.
- While i is valid or carry is greater than 0, continue the loop.
- If i is valid, add num[i] to carry and decrement i.
- Append carry % 10 to the result.
- Set carry to carry // 10.
- After the loop, reverse the result and return it.
Dry run
Start with i = 3 (the last digit) and carry = 9999. Each row is one pass of the loop.
| Step | i | num[i] | carry before | carry + num[i] | digit written | carry after |
|---|---|---|---|---|---|---|
| 1 | 3 | 0 | 9999 | 9999 | 9 | 999 |
| 2 | 2 | 0 | 999 | 999 | 9 | 99 |
| 3 | 1 | 0 | 99 | 99 | 9 | 9 |
| 4 | 0 | 1 | 9 | 10 | 0 | 1 |
| 5 | -1 | (none) | 1 | 1 | 1 | 0 |
After step 5, i is -1 and carry is 0, so the loop stops. The written digits are [9,9,9,0,1]. Reversing them gives [1,0,9,9,9], the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of num. The loop runs once per column, and there are n columns plus the leftover carry. Because k has at most five digits, the carry adds at most 10 columns past num, so the loop runs at most n + 10 times in O(n) time. The output holds about n + 10 digits, which is the only storage that grows, so the space is O(n) including the output and O(1) beyond it.
PythonTested in our runner
from typing import List, Optional
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
result = []
i = len(num) - 1
carry = k # k acts as the initial carry
while i >= 0 or carry > 0:
if i >= 0:
carry += num[i]
i -= 1
result.append(carry % 10) # ones place of this column
carry //= 10 # tens part moves left
result.reverse() # digits were written least significant first
return resultCommon mistakes
- Reading
num[i]before checkingi >= 0. In Python,num[-1]silently returns the last digit, so the carry gets the wrong value. Guard the read withif i >= 0. - Using only
while i >= 0as the loop condition. This drops the leading 1 in cases like 99 + 1. Keep the loop going while the carry is still greater than 0. - Writing
carry = num[i] + kand never dividing by ten. The full value of k is then added in every column. Divide the carry by 10 after each digit is written. - Calling
insert(0, digit)on each step. Each insert shifts the whole list, which makes the solution O(n^2). Append each digit, then reverse once. - Preallocating the Java result as
new int[num.length]. A carry can add a few digits past num, so the buffer needs extra room, such asnum.length + 11. - Converting num to a long or a fixed-width integer, then adding k. The array can hold 10^4 digits, so this overflows in every language here except with a big-number type.
Edge cases
- num = [0], k = 1 gives [1]. The single digit takes the carry without creating a new column.
- num = [9], k = 1 gives [1,0]. The carry leaves the last column and creates a new leading digit.
- num = [9,9,9], k = 1 gives [1,0,0,0]. A chain of 9s carries through every column.
- num = [1], k = 10000 gives [1,0,0,0,1]. Here k has more digits than num, so most output digits come from the carry.
- num of length 10^4 with every digit 9 and k = 10^4. The output is about 10^4 digits, and the single pass still runs in linear time.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Add to Array-Form of Integer, with how to answer them.
Unlock the follow-upsAdd to Array-Form of Integer FAQ
What is the time complexity of Add to Array-Form of Integer?
The optimal solution runs in O(n) time, where n is the length of num. Each column is handled once, and k adds at most about ten extra columns. The brute force that increments k times runs in O(k * n) in the worst case.
Why use a right-to-left carry pass for Add to Array-Form of Integer?
Carries move from the least significant digit toward the most significant digit. Processing from the right lets each column use the carry it receives from the column before it. The pass visits each column once and never converts the array into a fixed-width integer.
Can Add to Array-Form of Integer be solved in O(1) extra space?
Yes, if you do not count the output array. The optimal code keeps only an index, a carry and a loop variable, and the result array is the only storage that grows. The Java and C# versions also store the output in a list or buffer, which is the required result.
Why does the answer sometimes have one more digit than num?
A carry out of the leading digit creates a new column, as in 99 + 1 = 100. The loop keeps running while the carry is above zero, so that new column appears in the output.
Asked at
See which companies ask this — Pro
Related problems
- Plus One · same technique: Plus One (Handling Carry)
- Add Binary · same technique: Plus One (Handling Carry)
- Multiply Strings · same technique: Plus One (Handling Carry)
- Two Sum · same pattern: Array/Matrix Manipulation Patterns
- Contains Duplicate · same pattern: Array/Matrix Manipulation Patterns
- Happy Number · same pattern: Array/Matrix Manipulation Patterns
- Valid Anagram · same pattern: Array/Matrix Manipulation Patterns
- Missing Number · same pattern: Array/Matrix Manipulation Patterns
- Linked List Cycle · same pattern: Array/Matrix Manipulation Patterns
- Merge Sorted Array · same pattern: Array/Matrix Manipulation Patterns