703046. Sum of two numbers represented as arrays

Easy

Sum of two numbers represented as arrays

Slug: sum-of-two-numbers-represented-as-arrays3110

Difficulty: Easy

Id: 703046

Topic Tags: Arrays, Data Structures

Company Tags: Zoho, Accolite, Amazon

Summary

Given two integer arrays arr1 and arr2, each representing a number in base 10, find the sum of these numbers. The input arrays are guaranteed to be valid representations of non-negative integers.

The key concepts involved in this problem are arrays and data structures.

Detailed Explanation

To solve this problem, we can convert the two arrays into integers and then add them together. We can use a simple loop to iterate over the arrays, multiplying each digit by its corresponding power of 10 (since we're working with base 10) and adding it to our running total.

Here's a step-by-step breakdown of the solution:

  1. Initialize an integer result to 0.
  2. Iterate over the lengths of both input arrays using a for loop. Let's call these lengths n1 and n2.
  3. For each iteration, multiply the current digit of arr1 by 10^(n2-1) (since we're subtracting one from n2 because array indices start at 0).
  4. Add this product to result.
  5. Repeat steps 2-4 for arr2, multiplying each digit by 10^(n1-1).
  6. Return the sum of result and the result of adding arr1[0] and arr2[0].

Here's an ASCII art diagram illustrating this process:

    arr1: [1, 2, 3]
    arr2: [4, 5]

    Initialize result = 0
    Iterate over lengths:
      n1 = 3, n2 = 2
      Multiply current digit of arr1 by 10^(n2-1) = 10^1 = 10
      Add product to result = 0 + 10 = 10
      Repeat for arr2: multiply each digit by 10^(n1-1) = 10^2 = 100
      Add products to result = 10 + 100 = 110

    Return sum of result and first digits: 110 + (1+4) = 115

The time complexity for this solution is O(n1+n2), where n1 and n2 are the lengths of the input arrays. The space complexity is O(1), since we only use a constant amount of extra memory.

Optimized Solutions

Java

View on GeeksforGeeks
public int sumOfArrays(int[] arr1, int[] arr2) {
    int result = 0;
    for (int i = Math.max(arr1.length - 1, arr2.length - 1); i >= 0; i--) {
        result += (arr1[i] + arr2[i]) * (int)Math.pow(10, i);
    }
    return result;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.