0

Given two non-empty linked-lists representing two non-negative integers (in reverse order), add the two numbers and return the sum as a linked list.

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Everything works properly on my end, but there's a runtime error on leetcode and I can't quite figure out why. Here's my code:

const l1 = [2,4,3]
const l2 = [5,6,4]

const addTwoNumbers = (l1, l2) => {
    l1 = reverseLinkedList(l1)
    l2 = reverseLinkedList(l2)
    const l1sum = linkedListNum(l1)
    const l2sum = linkedListNum(l2)
    let sum = l1sum + l2sum
    // for 0 sum
    if (!sum) return [sum]
    const l3 = [];
    while (sum > 0) {
        l3.push(sum % 10);
        sum /= 10;
        sum = Math.trunc(sum)
    }
    return l3
}

const reverseLinkedList = (ll) => {
    let rev = []
    for (let i = ll.length - 1; i >= 0; i--) {
        rev.push(ll[i])
    }
    return rev
}

const linkedListNum = (ll) => {
    let sum
    for (let i = 0; i < ll.length; i++) {
        if (!i) {
            sum = ll[i]
            continue
        }
        sum *= 10
        sum += ll[i]
    }
    return sum
}

const answer = addTwoNumbers(l1,l2)
console.log(answer);
// answer output: [7,0,8]

Here's the error:

Line 65 in solution.js
             throw new TypeError(__serialize__(ret) + " is not valid value for thereturn type ListNode")
             ^
TypeError: [null] is not valid value for the expected return type ListNode
    Line 65: Char 20 in solution.js (Object.<anonymous>)
    Line 16: Char 8 in rumner.is (Object.runner)
    Line 49: Char 26 in solution.js (Object.<anonymous>)
    Line 1251: Char 30 in loader.js (Module._compile)
    Line 1272: Char 10 in loader.js (Object.Module._extensions..is)
    Line 1100: Char 32 in loader.is (Module.load)
    Line 962: Char 14 in loader.js (Function.Module._load)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    Line 17: Char 47 in run_main_module.js

Unrelated: This is my first question asked on stack overflow, let me know how I did.

3
  • You did good, but the error probably should be text instead of a link to a screenshot. Commented Jun 23, 2021 at 1:54
  • 2
    But what you have isn’t a linked list… it’s just an array. Commented Jun 23, 2021 at 2:09
  • @Terry this challenge started out in different languages and was translated to JS, seemingly without a LinkedList class polyfill. Notice that this a Leetcode question Commented Jun 23, 2021 at 2:22

3 Answers 3

4

There are far easier methods of achieving this by using modern array methods.

  1. Create a number from each array

  2. Add them together

  3. Coerce that back to a string, reverse it, and map the elements back to numbers.

const a1 = [2,4,3];
const a2 = [5,6,4];

// Take an array, reverse it, join it up into a string
// again and make it a number
const getNumber = arr => Number(arr.reverse().join(''));

// Sum the numbers from each array
const getSum = (arr1, arr2) => getNumber(arr1) + getNumber(arr2);

// Coerce the number to a string, split it into an array
// and reverse it, and map the strings back to numbers
const getResult = sum => sum.toString().split('').reverse().map(Number);    

// Get the result
console.log(getResult(getSum(a1, a2)));

Sign up to request clarification or add additional context in comments.

3 Comments

This isn't a coding challenge site - it's a teaching tool and code encyclopedia.
This is a question from Leetcode. The challenge is to work with the linked list and carry-the-one, not to just convert to numbers, add, then convert it back
You're making a massive assumption that I know what Leetcode is. SO is here to provide answers, and when it's clear there's a better way of achieving the goal, there may be some that address that issue.
3

Why don't you just use already available methods in javascript?

Here's my solution:

const l1 = [2,4,3];
const l2 = [5,6,4];
  
function getNum(list) {
    const numStr = list
    .reverse()
    .join("");
    return Number(numStr);
  }
  
function getList(num) {
    return num
    .toString()
    .split("")
    .reverse()
    .map(Number);
  }
  
  const sum = getNum(l1) + getNum(l2);
  const result = getList(sum)
  console.log(result)

Or if you want to do it in a mathematical way:

const l1 = [2,4,3];
const l2 = [5,6,4];

function getNum(list) {
  return list
    .reduce((a, c, i) => a + c * (10 ** i));
}
  
function getList(num) {
  const list = []
  while(num !=0) {
    list.push(num % 10);
    num = Math.floor(num / 10)
  }
  return list;
}

const sum = getNum(l1) + getNum(l2);
const result = getList(sum)
console.log(result)

4 Comments

Doing so goes against the spirit of the challenge.
Really? I've solved a lot of coding problems. But nowhere I've found that you're not allowed to use built in methods!
This is a question from Leetcode. The challenge is to work with the linked list and carry-the-one, not to just convert to numbers, add, then convert it back
Hey @Samathingamajig, I've updated my solution.
2

if (!sum) return [sum] is the issue here. when the inputs are empty array like as seen in the snippet. The sum would be null and is causing this issue. You can fix this by initialising the sum in linkedListNum to 0. That way it will return [0] instead.

const l1 = []
const l2 = []

const addTwoNumbers = (l1, l2) => {
    l1 = reverseLinkedList(l1)
    l2 = reverseLinkedList(l2)
    const l1sum = linkedListNum(l1)
    const l2sum = linkedListNum(l2)
    let sum = l1sum + l2sum
    // for 0 sum
    if (!sum) return [sum] // here is the issue
    const l3 = [];
    while (sum > 0) {
        l3.push(sum % 10);
        sum /= 10;
        sum = Math.trunc(sum)
    }
    return l3
}

const reverseLinkedList = (ll) => {
    let rev = []
    for (let i = ll.length - 1; i >= 0; i--) {
        rev.push(ll[i])
    }
    return rev
}

const linkedListNum = (ll) => {
    let sum = 0; // initialize sum here
    for (let i = 0; i < ll.length; i++) {
        if (!i) {
            sum = ll[i]
            continue
        }
        sum *= 10
        sum += ll[i]
    }
    return sum
}

const answer = addTwoNumbers(l1,l2)
console.log(answer);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.