Add to Array-Form of Integer solution and explanation
9 more videos on this problem
LeetCode 989 | Add to Array-Form of Integer | Day 7 | 100 Days_LeetCode_Challenge | DSA with edSlashedSlash · 22:13 · 29K views
Add to Array-Form of Integer - Leetcode 989 - PythonNeetCodeIO · 12:35 · 11K views
Add Array To form Integer | Leetcode 989 | Zero To FAANG DSA BootcampHAIL CODING · 14:10 · 2K views
989. Add to Array-Form of Integer - JAVA (Detailed explanation + Live coding)Sourin Majumdar · 10:48 · 1K views
989. Add to Array-Form of Integer | LeetCode Daily ChallengeDeep Tech · 7:49 · 1K views
[LeetCode] 989. Add to Array-Form of IntegerCode Granate · 2:04 · 684 views
Add to Array-Form of Integer - Leetcode 989 - PythonTechError · 11:55 · 597 views
989. Add to Array-Form of Integer | LeetCode daily | C++Priyanshi Porwal · 13:02 · 514 views
LeetCode 989 : Add to Array Form of Integer || EASY || JAVA || Detailed SolutionCodeGPT · 16:42 · 493 views
989. Add to Array-Form of Integer - LeetCode Solution Using JavascriptVideos2Learn · 16:13 · 359 views
The problem
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 num, the array-form of an integer, and an integer k, return the array-form of the integer 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
Constraints:
1 <= num.length <= 1040 <= num[i] <= 9numdoes not contain any leading zeros except for the zero itself.1 <= k <= 104
Approach overview
Problem Overview: You’re given an integer represented as an array where each element is a digit. The goal is to add another integer k to this number and return the result in the same array-form format. Instead of converting the array to a large integer, perform digit-by-digit addition the same way you would do manual addition.
Approach 1: Divide and Conquer (O(n), O(1))
This approach treats the addition as repeated digit-level subproblems. Start from the least significant digit (the end of the array) and add the current digit with the last digit of k. Store the result digit and propagate the carry forward. Then reduce k using k //= 10 and continue until both the array digits and remaining carry are processed.
The key idea is decomposing the addition into smaller independent operations: digit addition and carry propagation. You iterate from right to left, update digits in place, and insert a new digit at the front if a carry remains. This avoids integer overflow and works efficiently even for very large numbers represented in arrays. Time complexity is O(n) where n is the number of digits, and extra space is O(1) ignoring the output.
This method relies on simple arithmetic operations and sequential array traversal, making it a natural fit for problems involving array manipulation and math-based digit operations.
Approach 2: Iterative Two-Pointer Technique (O(n), O(n))
This variation explicitly processes digits from both numbers using two logical pointers: one pointing to the end of the array and the other representing the current digit of k. At each step, extract k % 10 and combine it with the current array digit and carry. Append the resulting digit to a temporary list and update the carry.
The process continues until all digits from the array and integer k are consumed. Since digits are appended in reverse order, reverse the result at the end to produce the final array-form number. This mirrors the classic two-pointer digit addition used in problems like adding linked list numbers.
The algorithm performs a single pass across the digits, giving O(n) time complexity. The temporary result list requires O(n) extra space. This approach is often easier to reason about because each step explicitly models digit addition with carry using a forward iteration pattern common in two-pointer techniques.
Recommended for interviews: The iterative digit addition approach is what interviewers expect. It demonstrates that you understand how to simulate arithmetic operations directly on arrays without converting to large integers. Showing the straightforward carry-based solution first proves your grasp of the problem, while the optimized single-pass method highlights clean implementation and strong handling of edge cases such as leftover carry or extra digits in k.
Approach 1: Divide and Conquer
This approach involves breaking down the problem into smaller sub-problems, solving each sub-problem recursively, and combining the results to solve the larger problem. It's often used in sorting and searching algorithms, such as Merge Sort and Quick Sort.
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
arr = [12, 11, 13, 5, 6, 7]
mergeSort(arr)
print("Sorted array is", arr)class MergeSort {
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void sort(int arr[], int l, int r) {
if (l < r) {
int m = (l+r)/2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static void printArray(int arr[]) {
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[]) {
int arr[] = {12, 11, 13, 5, 6, 7};
System.out.println("Given Array");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.length-1);
System.out.println("Sorted array");
printArray(arr);
}
}#include <iostream>
#include <vector>
void merge(std::vector<int>& arr, int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
std::vector<int> L(n1);
std::vector<int> R(n2);
for (int i = 0; i < n1; i++)
L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(std::vector<int>& arr, int l, int r) {
if (l < r) {
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void printArray(const std::vector<int>& arr) {
for (int x : arr)
std::cout << x << " ";
std::cout << std::endl;
}
int main() {
std::vector<int> arr = {12, 11, 13, 5, 6, 7};
std::cout << "Given array is \n";
printArray(arr);
mergeSort(arr, 0, arr.size() - 1);
std::cout << "Sorted array is \n";
printArray(arr);
return 0;
}function mergeSort(arr) {
if (arr.length < 2) {
return arr;
}
const mid = Math.floor(arr.length / 2);
const left = arr.slice(0, mid);
const right = arr.slice(mid);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
const result = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
result.push(left[i]);
i++;
} else {
result.push(right[j]);
j++;
}
}
return result.concat(left.slice(i)).concat(right.slice(j));
}
const arr = [12, 11, 13, 5, 6, 7];
console.log("Sorted array is", mergeSort(arr));#include <stdio.h>
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
i = 0; j = 0; k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size) {
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("Sorted array is \n");
printArray(arr, arr_size);
return 0;
}using System;
class Program {
static void Merge(int[] arr, int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int[] L = new int[n1];
int[] R = new int[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
int a = 0, b = 0;
int k = l;
while (a < n1 && b < n2) {
if (L[a] <= R[b]) {
arr[k] = L[a];
a++;
} else {
arr[k] = R[b];
b++;
}
k++;
}
while (a < n1) {
arr[k] = L[a];
a++;
k++;
}
while (b < n2) {
arr[k] = R[b];
b++;
k++;
}
}
static void MergeSort(int[] arr, int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
MergeSort(arr, l, m);
MergeSort(arr, m + 1, r);
Merge(arr, l, m, r);
}
}
static void Main() {
int[] arr = {12, 11, 13, 5, 6, 7};
MergeSort(arr, 0, arr.Length - 1);
Console.WriteLine(string.Join(", ", arr));
}
}This Python implementation of Merge Sort uses recursion to sort the array. The array is divided into halves, recursively sorted, and merged.
Time Complexity: O(n log n) for the average and worst case.
Space Complexity: O(n) due to the recursion stack and merging process.
Approach 2: Iterative Two-Pointer Technique
This approach involves using two pointers or indices to traverse an array or linked list from two ends towards the center. It’s often applied to solve problems like palindrome checking, two-sum in a sorted array, and finding pairs in a sorted array.
def twoSum(nums, target):
left, right = 0, len(nums) - 1
while left < right:
if nums[left] + nums[right] == target:
return [left, right]
elif nums[left] + nums[right] < target:
left += 1
else:
right -= 1
return [-1, -1]
nums = [2, 3, 4, 5, 6, 7]
target = 9
result = twoSum(nums, target)
print("Indices:", result)public class TwoSum {
public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return new int[]{left, right};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[]{-1, -1};
}
public static void main(String[] args) {
TwoSum solution = new TwoSum();
int[] numbers = {2, 3, 4, 5, 6, 7};
int target = 9;
int[] result = solution.twoSum(numbers, target);
System.out.println("Indices: " + result[0] + ", " + result[1]);
}
}#include <iostream>
#include <vector>
std::vector<int> twoSum(std::vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
return {left, right};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return {-1, -1};
}
int main() {
std::vector<int> nums = {2, 3, 4, 5, 6, 7};
int target = 9;
std::vector<int> result = twoSum(nums, target);
std::cout << "Indices: " << result[0] << ", " << result[1] << std::endl;
return 0;
}function twoSum(nums, target) {
let left = 0, right = nums.length - 1;
while (left < right) {
let sum = nums[left] + nums[right];
if (sum === target) {
return [left, right];
} else if (sum < target) {
left++;
} else {
right--;
}
}
return [-1, -1];
}
const nums = [2, 3, 4, 5, 6, 7];
const target = 9;
const result = twoSum(nums, target);
console.log("Indices:", result);#include <stdio.h>
#include <stdlib.h>
void twoSum(int* nums, int numsSize, int target, int* result) {
int left = 0, right = numsSize - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
result[0] = left;
result[1] = right;
return;
} else if (sum < target) {
left++;
} else {
right--;
}
}
result[0] = -1;
result[1] = -1;
}
int main() {
int nums[] = {2, 3, 4, 5, 6, 7};
int target = 9;
int result[2];
twoSum(nums, 6, target, result);
printf("Indices: %d, %d\n", result[0], result[1]);
return 0;
}using System;
public class TwoSum {
public int[] TwoSumIndices(int[] nums, int target) {
int left = 0, right = nums.Length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
return new int[] {left, right};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[] {-1, -1};
}
static void Main() {
var solution = new TwoSum();
int[] nums = {2, 3, 4, 5, 6, 7};
int target = 9;
int[] result = solution.TwoSumIndices(nums, target);
Console.WriteLine("Indices: {0}, {1}", result[0], result[1]);
}
}This Python implementation uses the two-pointer technique on sorted arrays to efficiently find indices whose sum equals a target by adjusting pointers based on comparison outcomes.
Time Complexity: O(n) as each element can be traversed at most once.
Space Complexity: O(1) owing to constant space usage aside from input variables.
Approach 3: Simulation
We can start from the last digit of the array and add each digit of the array to k. Then, divide k by 10, and use the remainder as the current digit's value, with the quotient as the carry. Continue this process until the array is fully traversed and k = 0. Finally, reverse the answer array.
The time complexity is O(n), where n is the length of num. Ignoring the space consumption of the answer array, the space complexity is O(1).
function addToArrayForm(num: number[], k: number): number[] {
const ans: number[] = [];
for (let i = num.length - 1; i >= 0 || k > 0; --i) {
k += i >= 0 ? num[i] : 0;
ans.push(k % 10);
k = Math.floor(k / 10);
}
return ans.reverse();
}func addToArrayForm(num []int, k int) (ans []int) {
for i := len(num) - 1; i >= 0 || k > 0; i-- {
if i >= 0 {
k += num[i]
}
ans = append(ans, k%10)
k /= 10
}
slices.Reverse(ans)
return
}impl Solution {
pub fn add_to_array_form(num: Vec<i32>, k: i32) -> Vec<i32> {
let mut ans = Vec::new();
let mut k = k;
let mut i = num.len() as i32 - 1;
while i >= 0 || k > 0 {
if i >= 0 {
k += num[i as usize];
}
ans.push(k % 10);
k /= 10;
i -= 1;
}
ans.reverse();
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Divide and Conquer | Time Complexity: O(n log n) for the average and worst case. |
| Iterative Two-Pointer Technique | Time Complexity: O(n) as each element can be traversed at most once. |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Divide and Conquer (digit + carry propagation) | O(n) | O(1) | When modifying the input array directly and minimizing extra memory |
| Iterative Two-Pointer Technique | O(n) | O(n) | When building the result step-by-step in a new array for simpler implementation |
Frequently asked questions
Is Add to Array-Form of Integer easy or hard?
Add to Array-Form of Integer is classified as an Easy problem on LeetCode. The challenge mainly involves simulating manual addition using arrays and handling carry correctly. Developers comfortable with array traversal and basic math typically solve it in one pass.
Add to Array-Form of Integer Python/Java solution
Python and Java implementations follow the same logic: iterate from the end of the array, add digits with k and carry, update the current position or append to a result list, and continue until all digits are processed. Both languages achieve O(n) time complexity with straightforward arithmetic operations.
How to solve Add to Array-Form of Integer in O(n)?
Start from the last digit of the array and repeatedly add the last digit of k and any carry. Store the resulting digit using modulo 10 and update the carry using integer division. Continue until both the array digits and k are fully processed, then handle any remaining carry. This single pass ensures O(n) complexity.
What is the best approach for Add to Array-Form of Integer?
The best approach is digit-by-digit addition from the end of the array while maintaining a carry, similar to manual arithmetic. Iterate from the last index, add the current digit with k % 10 and carry, then update k using k // 10. This method runs in O(n) time and uses O(1) extra space if the input array is modified in place.
Is Add to Array-Form of Integer asked at Google/Amazon/Meta?
Array-based arithmetic and digit manipulation problems appear frequently in interviews at companies like Google, Amazon, and Meta. Variants include adding numbers stored in arrays or linked lists and managing carry propagation. The problem tests understanding of array traversal and basic math operations.
What data structure is used in Add to Array-Form of Integer?
The primary data structure is an array that stores each digit of the integer. The algorithm performs sequential traversal and updates digits while maintaining a carry value. Some implementations also use a dynamic list to build the result before reversing it.
What is the time complexity of Add to Array-Form of Integer?
The optimal solution runs in O(n) time where n is the number of digits in the array representation. Each digit is processed once while propagating the carry. Space complexity can be O(1) for in-place modification or O(n) if constructing a separate result array.
