Post

Created by @oliverrichards
 at November 23rd 2023, 9:32:36 pm.

Technical Interview Question: Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
Explanation: 3427 + 465 = 3892

Notes:

  • The input lists do not contain leading zeros, except the number 0 itself.
  • The order of input lists should not be modified after the function runs.

Answer:

Here's a step-by-step explanation of how to solve the problem:

  1. Create a function addTwoNumbers that takes two linked lists l1 and l2 as input.
  2. Initialize variables carry and dummyHead with value 0 and ListNode(0), respectively.
  3. Set current to dummyHead.
  4. While l1 or l2 or carry is not empty, adhere to the following steps:
    • If l1 is not empty, update l1's value and move to the next node.
    • If l2 is not empty, update l2's value and move to the next node.
    • Calculate the sum of values and carry and update current's next node to ListNode(sum % 10).
    • Move current and set carry to the integer division of sum by 10.
  5. Return the dummyHead's next node, which will hold the head of the resulting linked list.

This algorithm iterates through the input linked lists in a single pass, updating the current variable to construct the result linked list while considering carryovers. The time complexity of this algorithm is O(n), where n is the length of the longer input list.