Menu
CoddyTech

Add Two Numbers

You get two non-negative whole numbers, each stored as a singly linked list of its digits with the least significant digit first. In the first list, node i holds the digit values1[i] and links to node next1[i]. The second list works the same way with next2 and values2. In both lists -1 ends the list and the head is node 0. The nodes are not stored in list order, so follow the links.

Return the digits of the sum of the two numbers, least significant digit first.

Function

addTwoNumbers(next1: integer-array, values1: integer-array, next2: integer-array, values2: integer-array) → integer-array
next1integer-array
the index of the node each node of the first number links to, or -1 for its last node
values1integer-array
the digit held by each node of the first number
next2integer-array
the index of the node each node of the second number links to, or -1 for its last node
values2integer-array
the digit held by each node of the second number
Returnsinteger-array
the digits of the sum, least significant first

Constraints

  • 1 ≤ L1 ≤ 100, where L1 is the length of next1 and of values1.
  • 1 ≤ L2 ≤ 100, where L2 is the length of next2 and of values2.
  • 0 ≤ values1[i], values2[j] ≤ 9
  • Each entry of next1 is -1 or a node index of the first list, and each entry of next2 is -1 or a node index of the second list.
  • Starting at node 0, each list visits every one of its nodes exactly once and then reaches -1. There is no cycle.
  • No number has leading zeros: the last node of a list holds a digit other than 0, unless the list is the single digit 0.

Examples

Input
next1 = [2, -1, 1]values1 = [8, 6, 1]next2 = [2, -1, 1]values2 = [7, 5, 2]
Output
[5, 4, 1, 1]
Explanation
The first list visits nodes 0, 2, 1 and reads 8, 1, 6, the number 618. The second reads 7, 2, 5, the number 527. Their sum is 1145, so the answer is 5, 4, 1, 1.
challenge icon

Follow-up

How would you add the numbers if the lists stored the most significant digit first?

Reset code
def addTwoNumbers(next1, values1, next2, values2):
    # Write code here

Test #1

Test #2

Test #3

Arguments

next1 = [2, -1, 1]
values1 = [8, 6, 1]
next2 = [2, -1, 1]
values2 = [7, 5, 2]

Expected Output

[5, 4, 1, 1]