Javascript Coding Interview Questions

The easy approach to ‘Linked List’ and ‘Adding two numbers’ 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.

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

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


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) { = val; = null;

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

// creating first list, actual number is 249
head1 = new Node(9); = new Node(4); = new Node(2);
// creating second list, actual number is 456
head2 = new Node(6); = new Node(5); = 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 ? : 0;
let headValue2 = head2 ? : 0;

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

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


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