We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Add to Array-Form of Integer

Number: 1031

Difficulty: Easy

Paid? No

Companies: Meta, Bloomberg, Amazon, Zoho, ByteDance


Problem Description

Given an array-form representation of an integer and an integer k, return the array-form of the sum (num + k).


Key Insights

  • Instead of converting the array to an integer, simulate the addition process digit by digit.
  • Start processing from the least significant digit (i.e., from the right end of the array).
  • Use a carry that incorporates both the current digit and any remaining part of k.
  • Continue processing until both the entire array and any carry have been exhausted.

Space and Time Complexity

Time Complexity: O(max(n, m)) where n is the number of digits in the array and m is the number of digits in k. Space Complexity: O(max(n, m)) for storing the result.


Solution

The solution involves iterating through the array from right to left and adding the corresponding digit of k (included in a carry variable). At each step, add the digit (if available) and the current carry, then store the least significant digit of the sum and update the carry (using division by 10). After the loop, if there is any remaining carry, break it into individual digits and add them to the result. Finally, reverse the resultant digit array to present them in the correct order.


Code Solutions

# Function to add array-form number with integer k
def addToArrayForm(num, k):
    i = len(num) - 1  # Start from the last index of num
    carry = k         # Initialize carry with k
    result = []       # List to store result digits
    
    # Process each digit from right to left or until carry is exhausted
    while i >= 0 or carry > 0:
        if i >= 0:
            carry += num[i]  # Add current digit to carry
        result.append(carry % 10)  # Extract the last digit as part of the result
        carry //= 10    # Update carry by removing the last digit
        i -= 1         # Move to the previous digit
    
    result.reverse()   # Reverse the result list to obtain the correct order
    return result

# Example usage:
print(addToArrayForm([1, 2, 0, 0], 34))  # Expected output: [1,2,3,4]
← Back to All Questions