Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close

Add Two Numbers Represented By Lists Problem

Add Two Numbers Represented By Lists Problem Statement

You are given two non-empty linked lists representing two non-negative numbers. Each of their nodes contains a single decimal digit. The most significant digit comes first. Return a linked list representing the sum of these two numbers.

Example

{
"number1": [9, 9],
"number2": [1]
}

Output:

[1, 0, 0]

99 + 1 = 100.

Notes

No number will start from digit 0 except the number 0.

Constraints:

  • 1 <= length of a list <= 105
  • 0 <= value in a list node <= 9

Code For Add Two Numbers Represented By Lists Solution 1: Recursive

/*
Asymptotic complexity in terms of the total length of input linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/

int length(LinkedListNode* head) {
    int length = 0;
    while(head) {
        head = head->next;
        length++;
    }
    return length;
}

LinkedListNode* recursive_helper(
    LinkedListNode* number1, LinkedListNode* number2, int& carry, int difference) {

    if (!number1) {
       return nullptr;
    }

    LinkedListNode* result = new LinkedListNode(0);

    // Note that when one list is shorted than another, we effectively use '0' as missing values
    // in the shorter list.
    // For example, with 1->2->3->4 and 6->7, the second list is "virtually" made 0->0->6->7.
    // Instead of actually grow the list, we use argument called \`difference\` to do that "virtually".
    result->next = recursive_helper(
        number1->next, (difference > 0 ? number2 : number2->next), carry, difference - 1);

    int sum = number1->value + (difference > 0 ? 0 : number2->value) + carry;
    carry = sum / 10;
    result->value = sum % 10;

    return result;
}

LinkedListNode *add_two_numbers(LinkedListNode *number1, LinkedListNode *number2) {
    int length1 = length(number1);
    int length2 = length(number2);

    if(length1 < length2) {
        swap(number1, number2);
    }

    // Shorter list has abs(length2 - length1) fewer nodes than the longer one.
    int difference = abs(length2 - length1);
    int carry = 0;

    LinkedListNode* answer = recursive_helper(number1, number2, carry, difference);

    if(carry > 0) {
        // Insert a node at the front.
        LinkedListNode* temp = new LinkedListNode(carry);
        temp->next = answer;
        answer = temp;
    }
    return answer;
}

Code For Add Two Numbers Represented By Lists Solution 2: Iterative Using Stack

/*
Asymptotic complexity in terms of the total length of the linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/

stack<int> fill_stack_from_list(LinkedListNode *list) {
    stack<int> result;
    while (list) {
        result.push(list->value);
        list = list->next;
    }
    return result;
}

int pop_from_stack_or_zero(stack<int> &s) {
    if (s.empty()) {
        return 0;
    } else {
        int result = s.top();
        s.pop();
        return result;
    }
}

LinkedListNode *add_two_numbers(LinkedListNode *number1, LinkedListNode *number2) {
    stack<int> stack1 = fill_stack_from_list(number1);
    stack<int> stack2 = fill_stack_from_list(number2);

    LinkedListNode* result = nullptr;

    int carry = 0;
    while (!stack1.empty() or !stack2.empty() or carry > 0) {
        int sum = pop_from_stack_or_zero(stack1) + pop_from_stack_or_zero(stack2) + carry;
        carry = sum / 10;

        LinkedListNode* node_to_insert = new LinkedListNode(sum % 10);
        node_to_insert->next = result;
        result = node_to_insert;
    }

    return result;
}

Code For Add Two Numbers Represented By Lists Solution 3: Iterative Without Using Stack

/*
Asymptotic complexity in terms of the total length of input linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/

LinkedListNode* reverse(LinkedListNode* head) {
    LinkedListNode *current_node = head, *previous_node = nullptr, *next_node = nullptr;
    while(current_node) {
        next_node = current_node->next;
        current_node->next = previous_node;
        previous_node = current_node;
        current_node = next_node;
    }
    return previous_node;
}

LinkedListNode *add_two_numbers(LinkedListNode *number1, LinkedListNode *number2) {
    number1 = reverse(number1);
    number2 = reverse(number2);

    LinkedListNode *answer = nullptr;
    LinkedListNode *temp = nullptr;
    int carry = 0;

    while(number1 or number2 or carry > 0) {
        int sum = 0;

        if (number1) {
            sum += number1->value;
            number1 = number1->next;
        }
        if (number2) {
            sum += number2->value;
            number2 = number2->next;
        }

        sum += carry;
        temp = new LinkedListNode(sum % 10);
        temp->next = answer;
        answer = temp;

        carry = sum / 10;
    }
    return answer;
}

Code For Add Two Numbers Represented By Lists Solution 4: Iterative


"""
Asymptotic complexity in terms of the total length of input linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
"""

def fill_stack_from_list(list):
    result = []
    while list:
        result.append(list.value)
        list = list.next
    return result

def pop_from_stack_or_zero(stack):
    if not stack:
        return 0
    else:
        return stack.pop()

def add_two_numbers(number1, number2):
    stack1 = fill_stack_from_list(number1)
    stack2 = fill_stack_from_list(number2)

    result = None
    carry = 0

    while stack1 or stack2 or carry > 0:
        sum = pop_from_stack_or_zero(stack1) + pop_from_stack_or_zero(stack2) + carry
        carry = sum // 10

        node_to_insert = LinkedListNode(sum % 10)
        node_to_insert.next = result
        result = node_to_insert

    return result

Code For Add Two Numbers Represented By Lists Solution 5: Iterative Using Stack.P


"""
Asymptotic complexity in terms of the total length of the linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
"""

def fill_stack_from_list(list):
    result = []
    while list:
        result.append(list.value)
        list = list.next
    return result

def pop_from_stack_or_zero(stack):
    if not stack:
        return 0
    else:
        return stack.pop()

def add_two_numbers(number1, number2):
    stack1 = fill_stack_from_list(number1)
    stack2 = fill_stack_from_list(number2)

    result = None
    carry = 0

    while stack1 or stack2 or carry > 0:
        sum = pop_from_stack_or_zero(stack1) + pop_from_stack_or_zero(stack2) + carry
        carry = sum // 10

        node_to_insert = LinkedListNode(sum % 10)
        node_to_insert.next = result
        result = node_to_insert

    return result

Code For Add Two Numbers Represented By Lists Solution 6: Recursive


"""
Asymptotic complexity in terms of the total length of input linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
"""


def reverse(head):
    current_node = head
    previous_node = None

    while current_node:
        next_node = current_node.next
        current_node.next = previous_node
        previous_node = current_node
        current_node = next_node

    return previous_node

def add_two_numbers(number1, number2):
    number1 = reverse(number1)
    number2 = reverse(number2)

    answer = None
    temp = None
    carry = 0

    while number1 or number2 or carry > 0:
        sum = 0

        if number1:
            sum += number1.value
            number1 = number1.next
        if number2:
            sum += number2.value
            number2 = number2.next

        sum += carry
        node_to_insert = LinkedListNode(sum % 10)
        node_to_insert.next = answer
        answer = node_to_insert

        carry = sum // 10

    return answer


We hope that these solutions to the add two numbers represented by list problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart's FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Add Two Numbers Represented By Lists Problem

Add Two Numbers Represented By Lists Problem Statement

You are given two non-empty linked lists representing two non-negative numbers. Each of their nodes contains a single decimal digit. The most significant digit comes first. Return a linked list representing the sum of these two numbers.

Example

{
"number1": [9, 9],
"number2": [1]
}

Output:

[1, 0, 0]

99 + 1 = 100.

Notes

No number will start from digit 0 except the number 0.

Constraints:

  • 1 <= length of a list <= 105
  • 0 <= value in a list node <= 9

Code For Add Two Numbers Represented By Lists Solution 1: Recursive

/*
Asymptotic complexity in terms of the total length of input linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/

int length(LinkedListNode* head) {
    int length = 0;
    while(head) {
        head = head->next;
        length++;
    }
    return length;
}

LinkedListNode* recursive_helper(
    LinkedListNode* number1, LinkedListNode* number2, int& carry, int difference) {

    if (!number1) {
       return nullptr;
    }

    LinkedListNode* result = new LinkedListNode(0);

    // Note that when one list is shorted than another, we effectively use '0' as missing values
    // in the shorter list.
    // For example, with 1->2->3->4 and 6->7, the second list is "virtually" made 0->0->6->7.
    // Instead of actually grow the list, we use argument called \`difference\` to do that "virtually".
    result->next = recursive_helper(
        number1->next, (difference > 0 ? number2 : number2->next), carry, difference - 1);

    int sum = number1->value + (difference > 0 ? 0 : number2->value) + carry;
    carry = sum / 10;
    result->value = sum % 10;

    return result;
}

LinkedListNode *add_two_numbers(LinkedListNode *number1, LinkedListNode *number2) {
    int length1 = length(number1);
    int length2 = length(number2);

    if(length1 < length2) {
        swap(number1, number2);
    }

    // Shorter list has abs(length2 - length1) fewer nodes than the longer one.
    int difference = abs(length2 - length1);
    int carry = 0;

    LinkedListNode* answer = recursive_helper(number1, number2, carry, difference);

    if(carry > 0) {
        // Insert a node at the front.
        LinkedListNode* temp = new LinkedListNode(carry);
        temp->next = answer;
        answer = temp;
    }
    return answer;
}

Code For Add Two Numbers Represented By Lists Solution 2: Iterative Using Stack

/*
Asymptotic complexity in terms of the total length of the linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/

stack<int> fill_stack_from_list(LinkedListNode *list) {
    stack<int> result;
    while (list) {
        result.push(list->value);
        list = list->next;
    }
    return result;
}

int pop_from_stack_or_zero(stack<int> &s) {
    if (s.empty()) {
        return 0;
    } else {
        int result = s.top();
        s.pop();
        return result;
    }
}

LinkedListNode *add_two_numbers(LinkedListNode *number1, LinkedListNode *number2) {
    stack<int> stack1 = fill_stack_from_list(number1);
    stack<int> stack2 = fill_stack_from_list(number2);

    LinkedListNode* result = nullptr;

    int carry = 0;
    while (!stack1.empty() or !stack2.empty() or carry > 0) {
        int sum = pop_from_stack_or_zero(stack1) + pop_from_stack_or_zero(stack2) + carry;
        carry = sum / 10;

        LinkedListNode* node_to_insert = new LinkedListNode(sum % 10);
        node_to_insert->next = result;
        result = node_to_insert;
    }

    return result;
}

Code For Add Two Numbers Represented By Lists Solution 3: Iterative Without Using Stack

/*
Asymptotic complexity in terms of the total length of input linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/

LinkedListNode* reverse(LinkedListNode* head) {
    LinkedListNode *current_node = head, *previous_node = nullptr, *next_node = nullptr;
    while(current_node) {
        next_node = current_node->next;
        current_node->next = previous_node;
        previous_node = current_node;
        current_node = next_node;
    }
    return previous_node;
}

LinkedListNode *add_two_numbers(LinkedListNode *number1, LinkedListNode *number2) {
    number1 = reverse(number1);
    number2 = reverse(number2);

    LinkedListNode *answer = nullptr;
    LinkedListNode *temp = nullptr;
    int carry = 0;

    while(number1 or number2 or carry > 0) {
        int sum = 0;

        if (number1) {
            sum += number1->value;
            number1 = number1->next;
        }
        if (number2) {
            sum += number2->value;
            number2 = number2->next;
        }

        sum += carry;
        temp = new LinkedListNode(sum % 10);
        temp->next = answer;
        answer = temp;

        carry = sum / 10;
    }
    return answer;
}

Code For Add Two Numbers Represented By Lists Solution 4: Iterative


"""
Asymptotic complexity in terms of the total length of input linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
"""

def fill_stack_from_list(list):
    result = []
    while list:
        result.append(list.value)
        list = list.next
    return result

def pop_from_stack_or_zero(stack):
    if not stack:
        return 0
    else:
        return stack.pop()

def add_two_numbers(number1, number2):
    stack1 = fill_stack_from_list(number1)
    stack2 = fill_stack_from_list(number2)

    result = None
    carry = 0

    while stack1 or stack2 or carry > 0:
        sum = pop_from_stack_or_zero(stack1) + pop_from_stack_or_zero(stack2) + carry
        carry = sum // 10

        node_to_insert = LinkedListNode(sum % 10)
        node_to_insert.next = result
        result = node_to_insert

    return result

Code For Add Two Numbers Represented By Lists Solution 5: Iterative Using Stack.P


"""
Asymptotic complexity in terms of the total length of the linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
"""

def fill_stack_from_list(list):
    result = []
    while list:
        result.append(list.value)
        list = list.next
    return result

def pop_from_stack_or_zero(stack):
    if not stack:
        return 0
    else:
        return stack.pop()

def add_two_numbers(number1, number2):
    stack1 = fill_stack_from_list(number1)
    stack2 = fill_stack_from_list(number2)

    result = None
    carry = 0

    while stack1 or stack2 or carry > 0:
        sum = pop_from_stack_or_zero(stack1) + pop_from_stack_or_zero(stack2) + carry
        carry = sum // 10

        node_to_insert = LinkedListNode(sum % 10)
        node_to_insert.next = result
        result = node_to_insert

    return result

Code For Add Two Numbers Represented By Lists Solution 6: Recursive


"""
Asymptotic complexity in terms of the total length of input linked lists \`n\`:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
"""


def reverse(head):
    current_node = head
    previous_node = None

    while current_node:
        next_node = current_node.next
        current_node.next = previous_node
        previous_node = current_node
        current_node = next_node

    return previous_node

def add_two_numbers(number1, number2):
    number1 = reverse(number1)
    number2 = reverse(number2)

    answer = None
    temp = None
    carry = 0

    while number1 or number2 or carry > 0:
        sum = 0

        if number1:
            sum += number1.value
            number1 = number1.next
        if number2:
            sum += number2.value
            number2 = number2.next

        sum += carry
        node_to_insert = LinkedListNode(sum % 10)
        node_to_insert.next = answer
        answer = node_to_insert

        carry = sum // 10

    return answer


We hope that these solutions to the add two numbers represented by list problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart's FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Worried About Failing Tech Interviews?

Attend our free webinar to amp up your career and get the salary you deserve.

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Accelerate your Interview prep with Tier-1 tech instructors
blue tick
360° courses that have helped 14,000+ tech professionals
blue tick
100% money-back guarantee*
Register for Webinar
All Blog Posts