~/coding-interview/leetcode-solutions-add-two-numbers-link-list.md

Add two numbers(reverse order) link list Problem - Leet Code Solution

// TL;DR

Traverse both lists simultaneously, sum digits plus carry, create a new node for each result digit. Don't forget the final carry — if it's 1, add one more node.

Add two numbers(reverse order) link list Problem - Leet Code Solution

Problem Statement

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 contain 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: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

leetcode add numbers

Solution

private static ListNode addTwoNumbersHelper(ListNode l1, ListNode l2, int carry) { 
    if (l1 == null && l2 == null && carry == 0) {
        return null;
    }

    int sum = carry;
    if (l1 != null) { sum += l1.val; }
    if (l2 != null) { sum += l2.val; }

    if (sum > 9) { 
        sum = sum - 10;
        carry = 1; 
    }
    else {
        carry = 0;
    }

    ListNode newNode = new ListNode(sum);
    newNode.next = addTwoNumbersHelper(l1 != null ? l1.next : null, l2 != null ? l2.next : null, carry);
    return newNode;
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    return addTwoNumbersHelper(l1, l2, 0);
}

Explanation

This problem is rather simple. Since, the number is represented as link list in reverse order. i.e. the first node represent the last digit of a number. So, you can just started adding number as you traverse the two link list.

  • Start with iterating both link list.
  • take sum of two nodes, and carry if previously set.
  • If the sum is more than single digit, set the carry.
  • Now, new sum is our new node.
  • Since, it will be last digit in the result number, and will be first node in link list.
  • Its next pointer will be the one which will come out in next round of sum.
  • So, we simply set its next and call same method in recursive manner. Which will again goes in recursive mode untill all link list is exhausted.
  • And, we get our link list as sum.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…