DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
FREEDOM251

Freedom251 › Blog › array

How to Add k to an Array-Form Integer (LeetCode 989): Algorithm, Code, and Edge Cases

By Freedom251 Team · · 7 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To solve LeetCode 989, add k to the digit array from right to left, exactly as in handwritten addition. Add each digit to the current value of k, append k % 10, replace k with integer division by 10, and continue while digits or carry remain. Reverse the collected digits once at the end. This avoids converting a value that may contain 10,000 digits into a native integer.

The result runs in O(n) time and uses O(1) auxiliary space beyond the returned array. The official statement defines array-form as digits represented “in left to right order”; see LeetCode 989.

As an Amazon Associate I earn from qualifying purchases.

What the problem asks

You receive an array num whose elements are decimal digits in normal order: the first element is the most significant digit and the last is the least significant digit. You also receive an integer k. Return another digit array representing num + k.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For example, [1, 2, 0, 0] represents 1,200, not four separate values. Adding 34 must produce [1, 2, 3, 4]. The input constraints are 1 ≤ num.length ≤ 104, 0 ≤ num[i] ≤ 9, no leading zero is present unless the number itself is zero, and 1 ≤ k ≤ 104. Because the array can contain 10,000 digits, converting the complete value to a machine integer is not a safe general solution.

#1 Best Overall
Sale
Cracking the Coding Interview: 189 Programming Questions and Solutions
  • Careercup, Easy To Read
  • Condition : Good
  • Compact for travelling

LeetCode’s canonical wording is: “The array-form of an integer num is an array representing its digits in left to right order.”

Why the addition starts at the right

Decimal addition determines the units digit first. At each position, the sum consists of the input digit at that position plus the still-unprocessed portion of k. The remainder after division by 10 is the digit that belongs in the answer; the quotient is exactly what must be carried into the next position on the left.

A useful simplification is to keep the entire remaining addend and carry in one variable, k. Instead of extracting a digit from k separately and then adding a carry, perform k += num[i]. The operations k % 10 and k // 10 then produce the output digit and the next carry in one step.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Algorithm, step by step

  1. Set i to num.length - 1, the rightmost input index, and create an empty answer list.
  2. While i ≥ 0 or k > 0, add num[i] to k when i is still valid.
  3. Append k % 10 to the answer. This is the current decimal digit.
  4. Replace k with integer division by 10. Any nonzero value is the carry or remaining higher-order part of the addend.
  5. Decrement i and repeat.
  6. The digits were collected from least significant to most significant, so reverse the answer and return it.

The loop condition must include k > 0. Once every input digit has been consumed, a remaining carry can still create one or more leading digits.

The invariant that makes the method correct

Before each iteration, k represents the part of the original addend that belongs at the current position and all positions to its left, including any carry entering that position from the right. If a digit remains in num, adding num[i] incorporates that position’s input value.

For any nonnegative integer x, x = 10 * floor(x / 10) + (x % 10). Therefore, appending k % 10 records exactly the current digit, while integer-dividing by 10 removes that digit and preserves the value needed for the next position. When i becomes negative, the same identity continues to emit the remaining digits of k. Reversing the emitted sequence restores the required most-significant-first order, so every input digit and every carry is represented exactly once.

Worked examples

Input Right-to-left processing Returned array
num = [1,2,0,0], k = 34 0 + 34 gives 4, carry 3; 0 + 3 gives 3; remaining digits are 2 and 1. [1,2,3,4] (1,200 + 34 = 1,234)
num = [2,7,4], k = 181 4 + 181 gives 5, carry 18; 7 + 18 gives 5, carry 1; 2 + 1 gives 3. [4,5,5] (274 + 181 = 455)
num = [2,1,5], k = 806 5 + 806 gives 1, carry 82; 1 + 82 gives 3, carry 8; 2 + 8 gives 0, carry 1; the leftover 1 becomes a prefix. [1,0,2,1] (215 + 806 = 1,021)

Final carry example

For [9,9,9] plus 1, the first three iterations append 0, 0, and 0 while carrying 1. After the index passes the front of the array, k is still 1, so the loop runs once more and appends 1. Reversing gives [1,0,0,0]. This is why the result may be one digit longer than num.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When the addend outlives the array

If num = [1] and k = 9,999, the array is exhausted after one iteration, but k still contains higher decimal positions. The same loop emits those positions without special-case code. Stopping only when i < 0 would lose them.

Reference implementations

Python

def addToArrayForm(num, k):
    ans = []
    i = len(num) - 1

    while i >= 0 or k > 0:
        if i >= 0:
            k += num[i]
        ans.append(k % 10)
        k //= 10
        i -= 1

    ans.reverse()
    return ans

Python’s // performs integer division. All values here are nonnegative, so it leaves exactly the desired carry.

JavaScript

function addToArrayForm(num, k) {
  const ans = [];
  let i = num.length - 1;

  while (i >= 0 || k > 0) {
    if (i >= 0) k += num[i];
    ans.push(k % 10);
    k = Math.floor(k / 10);
    i--;
  }

  ans.reverse();
  return ans;
}

Math.floor is used because JavaScript’s ordinary division returns a floating-point number. Under the stated constraint, k remains well within the exact-integer range, while the digit array itself can still represent a much longer number.

Java

public int[] addToArrayForm(int[] num, int k) {
    List<Integer> digits = new ArrayList<>();
    int i = num.length - 1;

    while (i >= 0 || k > 0) {
        if (i >= 0) k += num[i];
        digits.add(k % 10);
        k /= 10;
        i--;
    }

    Collections.reverse(digits);
    int[] result = new int[digits.size()];
    for (int j = 0; j < digits.size(); j++) {
        result[j] = digits.get(j);
    }
    return result;
}

The list is convenient because the result can grow by a leading digit. An implementation targeting a platform that accepts lists directly can return the reversed list instead of copying it into an array.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

C++

vector<int> addToArrayForm(vector<int>& num, int k) {
    vector<int> ans;
    int i = static_cast<int>(num.size()) - 1;

    while (i >= 0 || k > 0) {
        if (i >= 0) k += num[i];
        ans.push_back(k % 10);
        k /= 10;
        --i;
    }

    reverse(ans.begin(), ans.end());
    return ans;
}

Complexity and memory use

Each input digit is visited once. The loop may perform a few additional iterations for the remaining digits of k, but that amount is bounded by the number of decimal digits in the addend. The total running time is O(n), where n is the length of num. The returned array itself requires O(n) storage. Excluding that required output, the algorithm uses O(1) auxiliary variables: the index, the addend/carry, and temporary references.

The answer is collected backward and reversed once. Repeatedly inserting each new digit at the front can make an array implementation quadratic because every insertion may shift existing elements.

Alternative designs and their trade-offs

Approach Advantages Risks or costs
Right-to-left digit simulation Works for 10,000-digit inputs, is linear, and does not depend on big-integer libraries. Requires an explicit final reversal.
Convert the array to a native integer Short for tiny examples. Can overflow, lose precision, or be unavailable for the permitted input length; it violates the purpose of the exercise.
Use a language big-integer type Handles large values when the runtime supplies one. Adds conversion overhead and makes the solution less portable; the array-to-number conversion still has to be implemented safely.
Mutate num in place Can avoid a separate result allocation while processing existing positions. Requires careful handling when a final carry needs a new first element, and it changes the caller’s input.

For an interview or a general-purpose solution, the first approach is the clearest balance of numeric safety, predictable complexity, and preservation of the input.

Edge cases and failure modes

  • Carry creates a new leading digit: test values such as [9,9,9] + 1. The loop must continue after the first digit is processed.
  • The addend has more digits than the array: keep testing k > 0 after i becomes negative.
  • Zero in the middle: a digit such as the zero in [1,0,5] is meaningful and must be processed; only prohibited leading zeros are excluded from valid input.
  • Single-digit input: both [0] and [9] exercise the boundary where the answer may remain one digit or grow.
  • Wrong division operation: languages with floating-point division need an explicit floor or integer conversion. The carry must be an integer at every iteration.
  • Wrong output order: appending while moving right to left produces a reversed result. Forgetting the final reversal returns valid digits in the wrong order.
  • Mutating unintentionally: if callers may reuse num, build a new answer rather than overwriting its entries.
  • Assuming a fixed result length: allocate dynamically or account for the possible extra leading digit.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Testing checklist

A compact test set should cover both ordinary addition and structural boundaries:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • [1,2,0,0], 34 → [1,2,3,4]
  • [2,7,4], 181 → [4,5,5]
  • [2,1,5], 806 → [1,0,2,1]
  • [9,9,9], 1 → [1,0,0,0]
  • [0], 1 → [1]
  • [1], 9999 → [1,0,0,0,0]
  • A long array containing internal zeros, confirming that zeros are retained and no conversion to a native integer occurs.

For a formal solution note, the Doocs reference presents the same right-to-left simulation and complexity analysis: LeetCode 989 solution.

Practical decision rule

Use digit simulation whenever the input is already an array of decimal digits or its length is not guaranteed to fit a native type. Keep the original array unchanged unless the function contract explicitly permits mutation. In every language, the essential checks are the same: process from the last index, combine the digit with k, emit the remainder, carry with integer division, continue while either source remains, and reverse once.

Frequently Asked Questions

What if an implementation receives k = 0?

Although LeetCode 989 constrains k to at least 1, the same loop works for zero: it processes every input digit and returns an equivalent copy after reversing the collected digits.

Can the result be shorter than the input array?

No for valid, nonnegative inputs without leading zeros. Addition cannot remove a most-significant digit; the result has the same length or one additional digit when a final carry remains.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why not insert each calculated digit at the beginning of the answer?

Front insertion may shift all existing elements on every iteration, making the operation quadratic for long arrays. Appending and reversing keeps the total work linear.

Does this algorithm modify num?

The reference pattern only reads num and writes a separate answer. An in-place variant is possible, but it must handle a new leading digit and should be used only when mutation is acceptable.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

arrayData Structures and Algorithmsinteger arithmeticLeetCodeprogramming tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.