Add two numbers in LL

Linked-List Logic Building Medium

Given two non-empty linked lists l1 and l2 which represent two non-negative integers.


The digits are stored in reverse order with each node storing one digit.

Add two numbers and return the sum as a linked list.


  • The sum Linked List will be in reverse order as well.
  • The Two given Linked Lists represent numbers without any leading zeros, except when the number is zero itself.

Examples:

Input: l1 = head -> 5 -> 4, l2 = head -> 4

Output: head -> 9 -> 4

Explanation: l1 = 45, l2 = 4.

l1 + l2 = 45 + 4 = 49.

Input: l1 = head -> 4 -> 5 -> 6, l2 = head -> 1 -> 2 -> 3

Output: head -> 5 -> 7 -> 9

Explanation: l1 = 654, l2 = 321.

l1 + l2 = 654 + 321 = 975.

Input: l1 = head -> 1, l2 = head -> 8 -> 7

Constraints

  • 1 <= Number of nodes in each Linked List <= 100
  • 0 <= value of each node in both Linked List <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

Hints

  • Initialize variables carry = 0 for tracking carry-over from previous sum. dummy_head to store the result list. current pointer for traversal.
  • Compute sum = l1.val + l2.val + carry. Extract new_digit = sum % 10, and update carry = sum // 10. Create a new node with new_digit and attach it to the result list. Move l1 and l2 to their next nodes if they exist.

Company Tags

AMD Siemens Healthineers MongoDB Qualcomm Cloudflare Square Chewy KPMG Walmart Bungie Visa Wayfair Ernst & Young Flipkart GE Healthcare Splunk Freshworks Morgan Stanley Snowflake Nutanix Shopify Seagate Technology Alibaba McKinsey & Company Databricks Google Microsoft Amazon Meta Apple Netflix Adobe