Javascript Coding Interview Questions

Given two numbers represented by two lists, which will return the sum of the list. The sum list is a list representation of the addition of two input numbers.

Input:
List1: 9->4->2// represents number 249
List2: 6->5->4 // represents number 456

Output: 
Resultant list: 5->0->7 // represents number 705
Explanation: 249 + 456 = 705

Solution

Let’s learn how to create Node, Node will have its own data and pointer which will point to the next Node.

// singly-linked list.

class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}

now, Let’s create two linked list, example -

// creating first list, actual number is 249
head1 = new Node(9);
head1.next = new Node(4);
head1.next.next = new Node(2);
// creating second list, actual number is 456
head2 = new Node(6);
head2.next = new Node(5);
head2.next.next = new Node(4);
NOTE — nodes are in reverse order

Let’s pass head1 and head2 to addTwoLists method,

sumofTwoNumberList = addTwoLists(head1, head2);

The final solution will look like this,

  • We have reversed linked lists and we need to iterate over each of them and add values from both lists to each other. As a result, we need to return a new linked list with the sum of the values.
  • We need to carry out value. Because you have to have a single digit value in every node. If you add 5 + 5 the result is 10, so you live 0 in the recent node and move 1 to the next node. And in the next node, you will add 1 to the sum.
let carryOver = 0
let addTwoLists = function(head1, head2) {
if(!head1 && !head2 && carryOver === 0) {
return null;
}

let headValue1 = head1 ? head1.data : 0;
let headValue2 = head2 ? head2.data : 0;

let sum = carryOver + headValue1 + headValue2;
carryOver = Math.floor(sum/10);
let nextHead1 = head1 ? head1.next : null;
let nextHead2 = head2 ? head2.next : null;

return {
value: sum % 10,
next: addTwoLists(nextHead1, nextHead2)
};
};
addTwoLists(head1, head2)

Output,

Sum of 249+ 456 = 705

This problem is very popular in coding interviews.

Keep learning, keep growing!

Don’t forget to follow me for more such articles, and subscribe to our newsletter.

Let’s connect on LinkedIn!. Please read more for more data structure javascript questions.

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store