Add to Array-Form of Integer
The array form of an integer num is an array representing its digits in left-to-right order. For example, for num = 1321, the array form is [1,3,2,1]. Given the array form of an integer and an integer k, return the array form of their sum.
This is a carry state DP problem. Process the digits from right to left, maintaining a carry. Add the current digit plus k's digit (if any) plus any carry from the previous step. The new digit is the result modulo 10, and the carry is floor(result / 10).
The algorithm continues until all digits of the array are processed, k becomes 0, and carry is 0. The result is built in reverse and reversed at the end. This is O(max(n, log k)) time with O(max(n, log k)) space for the result.
Edge cases include empty array form (return digits of k), k = 0 (return original array), and the result having one more digit than the original (e.g., 999 + 1 = 1000).
The carry state DP processes digits from least significant to most significant, which is the reverse of how the array is stored. This is common in digit manipulation problems where the carry propagates from right to left. The while loop continues until all inputs and the carry are exhausted.
Example Input & Output
Empty array + 123.
1200+34=1234.
999+1=1000.
274+181=455.
k=0.
Algorithm Flow

Solution Approach
Process right-to-left, tracking carry. Add digits from both inputs plus carry. Build result and reverse.
Time O(max(n, log k)), Space O(max(n, log k)).
Best Answers
import java.util.*;
class Solution {
public List<Integer> solution(int[] num, int k) {
LinkedList<Integer> res=new LinkedList<>();
int c=0,i=num.length-1;
while (i>=0||k>0||c>0) {
int s=c;
if (i>=0) { s+=num[i]; i--; }
if (k>0) { s+=k%10; k/=10; }
res.addFirst(s%10);
c=s/10;
}
return res;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
