Katkat

Add One to an Integer Stored as Digits Without ArrayList

OracleBackend Engineer · Onsite

Last updated

This problem tests array manipulation skills and the ability to handle carry-over logic in fixed-size numerical representations.

Problem Statement

Given an array of digits representing a non-negative integer, increment the integer by one and return the resulting array. The digits are stored such that the most significant digit is at the index 0.

Because the input array represents a fixed-size integer, if the increment causes an overflow (e.g., [9, 9] becomes [1, 0, 0]), you must return a new array with the appropriate size. You are not permitted to convert the array to a primitive integer type or use dynamic collection classes like ArrayList or List to build the result; you must manage the array memory explicitly.

Function Signature

int[] plusOne(int[] digits)

Constraints

  • 1 <= digits.length <= 1000
  • 0 <= digits[i] <= 9
  • The integer does not contain leading zeros unless the integer is exactly [0].

Examples

Example 1: Input: digits = [1, 2, 3] Output: [1, 2, 4] Explanation: 123 + 1 = 124.

Example 2: Input: digits = [9, 9] Output: [1, 0, 0] Explanation: 99 + 1 = 100.

Edge Cases

  • Single digit array (e.g., [9] -> [1, 0], [0] -> [1]).
  • Array with trailing nines (e.g., [8, 9, 9] -> [9, 0, 0]).

Hints

Hint 1

Start by incrementing the last digit and checking if it becomes 10.

Hint 2

If the digit becomes 10, set it to 0 and carry the 1 over to the next index on the left.

Hint 3

If you finish iterating through all digits and still have a carry of 1, you must create a new array of size N+1 with the first element as 1.

Follow-up questions

  • How would you modify your solution if the input represented a negative number using a sign flag or a separate sign digit?
  • What is the time complexity of your solution, and can it be optimized if you are allowed to modify the input array in-place?
  • How would the logic change if you were asked to add an arbitrary integer K (where K > 1) instead of just one?