Add two numbers represented by two arrays
Filed under Salesforce
Free read 2 of 3Determine if the arrays represent numbers with the most significant digit at index 0.
The question
Given two arrays representing non-negative integers (each element is a digit), return a new array representing their sum.
Constraints
- Arrays can have different lengths
- Handle carry-over during addition
- Result should be an array of digits
Examples
- Input
- [1, 2, 3], [4, 5]
- Output
- [1, 6, 8]
- Why
- 123 + 45 = 168
Approach
Determine if the arrays represent numbers with the most significant digit at index 0.
Use two pointers starting from the end of both arrays. Add digits and carry.
Store sums in a list and reverse it at the end, or insert at the beginning.
Empty arrays, arrays with single digits, and final carry.
Solution
O(max(N, M)) time, O(max(N, M)) space
def add_arrays(a, b):
i, j, carry = len(a)-1, len(b)-1, 0
res = []
while i >= 0 or j >= 0 or carry:
s = (a[i] if i >= 0 else 0) + (b[j] if j >= 0 else 0) + carry
res.append(s % 10)
carry = s // 10
i, j = i - 1, j - 1
return res[::-1]
Tips
- What they are testing: Test with different array lengths and cases requiring a carry at the most significant digit.
- Common mistake: Failing to handle the carry after the loop finishes or misaligning indices when lengths differ.
Follow-ups
- Provide corner test cases and their outputs.
Related Salesforce questions
Collected from public candidate posts and coding forums. Updated Nov 2026.