Code With Coffie
  • HOME
  • ABOUT US
  • PORTFOLIO
  • AI
    • AGENTIC AI
    • Generative AI
    • LangChain
    • LangGraph
    • LLM
    • MCP
    • RAG
  • TUTORIAL
    • MYSQL
      • DATETIME
    • DSA
      • LEETCODE
    • GIT
    • Docker
    • INTERVIEW
    • PROGRAMME
      • STAR PATTERN PROGRAMME
  • PYTHON
    • DJANGO
    • FLASK
    • FastAPI
    • Matplotlib
    • NumPy
    • Pandas
    • STREAMLIT
  • JAVASCRIPT
    • Vue.js
  • PHP
    • PHP OOPS
    • LARAVEL
    • WORDPRESS
  • NEXTERP
  • Home
  • Blog
  • LeetCode
  • LeetCode 2: Add Two Numbers in PHP | Step-by-Step Solution

LeetCode 2: Add Two Numbers in PHP | Step-by-Step Solution

Oct 04, 2026 by codewithhemu
LeetCode 2PHPMediumLinked ListData Structures

LeetCode Problem 2, Add Two Numbers, is a popular coding interview question that helps developers understand linked lists, arithmetic operations, and carry handling.

In this tutorial, we will solve the Add Two Numbers problem using PHP. We will explain the problem statement, understand linked lists, build the solution step by step, walk through a detailed dry run, and analyze the time and space complexity.

1. Problem Statement

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each node contains a single digit.

Your task is to add the two numbers and return their sum as a linked list.

You can assume that the numbers do not contain any leading zeros, except for the number 0 itself.

Example 1

Input:

l1 = [2,4,3]

l2 = [5,6,4]

Linked List Representation

First number:

2→4→3→NULL

Second number:

5→6→4→NULL

Output:

7→0→8→NULL

Explanation: The first linked list represents 342, and the second represents 465. Their sum is 807, which is stored in reverse order as [7,0,8].

Example 2

Input / Output
Input:
l1 = [0]
l2 = [0]

Output:
[0]

Explanation: 0 + 0 = 0.

Example 3

Input / Output
Input:
l1 = [9,9,9,9,9,9,9]
l2 = [9,9,9,9]

Output:
[8,9,9,9,0,0,0,1]

Explanation: The two linked lists represent 9,999,999 and 9,999. Their sum is 10,009,998, which is returned in reverse order.

2. Understanding a Linked List

A linked list is a linear data structure in which each element is stored in a node. Each node contains a value and a reference to the next node.

Unlike an array, linked list nodes do not have to be stored in consecutive memory locations. Each node points to the next node in the sequence.

Example of a singly linked list

2→4→3→NULL

Each circle represents a node. The arrow represents the next pointer, which connects the current node to the next node. NULL indicates the end of the linked list.

In this problem, each node contains one digit, and the digits are stored in reverse order. Therefore, [2,4,3] represents the number 342, not 243.

3. Understanding the Addition

Before writing the PHP code, let’s understand how normal addition works.

Consider adding 342 and 465:

Step 1: Add the units digits

2 + 5 = 7

Write 7 in the result. Carry = 0.


Step 2: Add the tens digits

4 + 6 = 10

Write 0 in the result and carry 1 to the next position.


Step 3: Add the hundreds digits

3 + 4 + 1 = 8

Write 8 in the result. Carry = 0.


Final result:

7→0→8→NULL

The main idea is to process the linked lists from beginning to end, add the digits at each position, and maintain a carry for the next position.

4. Approach to Solve the Problem

We can solve this problem efficiently using a simple traversal of both linked lists and a carry variable.

  • Initialize a dummy node to serve as the starting point of the result linked list.
  • Maintain a pointer called current to build the result.
  • Initialize carry = 0.
  • Traverse both linked lists while either list has remaining nodes or a carry exists.
  • Read the current digits from each list. If a list has ended, use 0 for that digit.
  • Add both digits and the carry.
  • Calculate the new digit using the modulo operator and update the carry using integer division.
  • Create a new node for the resulting digit and append it to the result.
  • Move the pointers to the next nodes and repeat until all digits and carry are processed.
  • Return the next node of the dummy node as the final answer.

5. PHP Solution

LeetCode provides the ListNode class for this problem. The following is the complete solution that fits the LeetCode PHP editor.

PHPLeetCode Solution
class Solution {
    function addTwoNumbers($l1, $l2) {
        $dummy = new ListNode(0);
        $current = $dummy;
        $carry = 0;

        while ($l1 !== null || $l2 !== null || $carry > 0) {
            $sum = $carry;

            if ($l1 !== null) {
                $sum += $l1->val;
                $l1 = $l1->next;
            }

            if ($l2 !== null) {
                $sum += $l2->val;
                $l2 = $l2->next;
            }

            $carry = intdiv($sum, 10);
            $digit = $sum % 10;

            $current->next = new ListNode($digit);
            $current = $current->next;
        }

        return $dummy->next;
    }
}
Note: Do not add a second ListNode class in the LeetCode editor if it is already provided in the problem template. Submit only the Solution class.

6. Explaining the PHP Code Line by Line

Step 1: Create a Dummy Node

PHP
$dummy = new ListNode(0);
$current = $dummy;

The dummy node is an initial placeholder for the result linked list. It simplifies the process of inserting the first digit because we do not need separate logic for the first node.

The current pointer tracks the last node in the result list, allowing us to append each new digit.

Step 2: Initialize Carry

PHP
$carry = 0;

When adding two digits, their sum may be 10 or greater. The carry stores the extra value that needs to be added to the next digit position.

Step 3: Traverse Both Lists

PHP
while ($l1 !== null || $l2 !== null || $carry > 0) {
    $sum = $carry;
}

The loop continues while either linked list has a remaining node or there is a carry to process. This ensures that lists of different lengths and any final carry are handled correctly.

Step 4: Add the Current Digits

PHP
if ($l1 !== null) {
    $sum += $l1->val;
    $l1 = $l1->next;
}

if ($l2 !== null) {
    $sum += $l2->val;
    $l2 = $l2->next;
}

We add the values from both lists if the current nodes exist. If one list has ended, it contributes 0. Each pointer then advances to the next node.

Step 5: Calculate the Digit and Carry

PHP
$carry = intdiv($sum, 10);
$digit = $sum % 10;

We use intdiv() to get the integer quotient and the modulo operator to get the remainder.

  • $sum % 10 gives the digit to store in the current result node.
  • intdiv($sum, 10) gives the carry for the next position.

For example, if the sum is 15, the digit is 5 and the carry is 1.

Step 6: Create the Result Node

PHP
$current->next = new ListNode($digit);
$current = $current->next;

A new linked list node is created for the calculated digit and attached to the end of the result. The current pointer then advances to this newly created node.

Step 7: Return the Result

PHP
return $dummy->next;

The dummy node is only a placeholder, so we return the node after it, which is the actual head of the resulting linked list.

7. Dry Run with Example

Let’s take the input:

Input
l1 = [2,4,3]
l2 = [5,6,4]

These linked lists represent 342 and 465 respectively.

StepDigit 1Digit 2Carry InSumResult DigitCarry Out
1250770
24601001
3341880

Step 1: Add 2 and 5

2 + 5 + 0 = 7. The result digit is 7, and the carry is 0.

Current result

7→NULL

Step 2: Add 4 and 6

4 + 6 + 0 = 10. The result digit is 0, and the carry is 1.

Current result

7→0→NULL

Step 3: Add 3 and 4 with Carry

3 + 4 + 1 = 8. The result digit is 8, and the carry becomes 0.

Final result

7→0→8→NULL

Output: [7,0,8]

The resulting linked list represents the number 807 when read in reverse order.

8. Handling Different Lengths

One linked list may contain more digits than the other. Our solution handles this by adding a digit only when its current node exists.

For example:

Input
l1 = [9,9,9]
l2 = [1]

We calculate:

  • 9 + 1 = 10 → digit 0, carry 1.
  • 9 + 0 + 1 = 10 → digit 0, carry 1.
  • 9 + 0 + 1 = 10 → digit 0, carry 1.
  • Both lists have ended, but the carry remains 1, so we create one more node.

Final linked list

0→0→0→1→NULL

Output: [0,0,0,1], representing 1000.

9. Why Do We Use a Dummy Node?

A dummy node is a temporary starting node that simplifies linked list construction. Without it, we would need special handling to initialize the head when inserting the first result digit.

Using a dummy node means every result digit can be appended using the same logic. At the end, we return $dummy->next, skipping the placeholder.

10. Time and Space Complexity

Time Complexity: O(max(n, m))

Here, n is the number of nodes in the first linked list and m is the number of nodes in the second linked list.

The algorithm traverses each linked list once and processes one digit per iteration. Therefore, the time complexity is O(max(n, m)), with at most one extra iteration for a final carry.

Space Complexity: O(max(n, m))

The result is stored in a new linked list. In the worst case, the result may have one more digit than the longer input list because of a final carry. The auxiliary space is O(1) apart from the output linked list.

Complexity Summary
  • Time Complexity: O(max(n, m))
  • Auxiliary Space: O(1), excluding the result
  • Output Space: O(max(n, m))

11. Common Mistakes to Avoid

  • Reading digits in the wrong order: The linked lists store digits in reverse order, so traverse from the head.
  • Forgetting the carry: Always add the carry from the previous position to the current sum.
  • Assuming both lists have the same length: Check each pointer independently and use 0 when a list has ended.
  • Ignoring the final carry: The loop must continue while the carry is greater than zero.
  • Returning the dummy node: Return $dummy->next, not the dummy node itself.
  • Converting the full linked list into an integer: Large inputs may exceed the native integer range. Perform digit-by-digit addition instead.

12. Frequently Asked Questions

Q1. What is LeetCode Problem 2?

LeetCode 2, Add Two Numbers, asks you to add two non-negative integers represented by linked lists in reverse digit order and return the result as a linked list.

Q2. Why are the digits stored in reverse order?

Reverse order allows us to start adding from the units digit at the head of each linked list, just like normal arithmetic addition.

Q3. What is the time complexity of Add Two Numbers?

The time complexity is O(max(n, m)), where n and m are the lengths of the two input linked lists.

Q4. Why do we use a carry variable?

The carry stores the extra value when the sum of digits is 10 or more, so it can be added to the next position.

Q5. Why is a dummy node useful?

A dummy node simplifies the construction of the result linked list by eliminating the need for special handling of the first node.

Q6. Can we solve this problem without converting the lists into integers?

Yes. Digit-by-digit addition directly on the linked lists avoids integer overflow and works efficiently even for long inputs.

Q7. What happens if the two linked lists have different lengths?

When one list ends, the algorithm treats its missing digits as 0 while continuing to process the other list and any remaining carry.

13. Conclusion

LeetCode 2: Add Two Numbers is an excellent problem for understanding linked list traversal, arithmetic operations, and carry management.

By using a dummy node, two pointers, and a carry variable, we can build the resulting linked list in a single traversal without converting the entire numbers into integers.

Key Takeaways
  • Linked lists represent numbers in reverse digit order.
  • Process one digit from each list at a time.
  • Maintain a carry to handle sums greater than 9.
  • Use a dummy node to simplify result construction.
  • Achieve O(max(n, m)) time complexity.

Practice this problem to strengthen your understanding of linked lists and prepare for technical coding interviews.

  • Share:
Previous Article LeetCode 3: Longest Substring Without Repeating Characters
Next Article Agentic AI vs Generative AI: Key Differences, Examples, Benefits, and Future
No comments yet! You be the first to comment.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

category

  • AGENTIC AI (2)
  • DATETIME (6)
  • DJANGO (1)
  • Docker (1)
  • DSA (22)
  • DSA PRACTICE (4)
  • GIT (1)
  • INTERVIEW (3)
  • JAVASCRIPT (69)
  • LARAVEL (41)
  • LeetCode (3)
  • MYSQL (45)
  • PHP (21)
  • PHP OOPS (16)
  • PROGRAMME (1)
  • PYTHON (11)
  • RAG (5)
  • REACT JS (6)
  • STAR PATTERN PROGRAMME (7)
  • Uncategorized (21)
  • Vue.js (5)
  • WORDPRESS (15)

Archives

  • October 2026
  • September 2026
  • July 2026
  • June 2026
  • May 2026
  • March 2026
  • October 2025
  • September 2025
  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • January 2023

Tags

Certificates Education Instructor Languages School Member

Building reliable software solutions for modern businesses. Sharing practical tutorials and real-world project insights to help developers grow with confidence.

GET HELP

  • Home
  • Portfolio
  • Privacy Policy
  • Terms & Conditions
  • Disclaimer
  • Contact Us

PROGRAMS

  • Software Development
  • Performance Optimization
  • System Architecture
  • Project Consultation
  • Technical Mentorship

CONTACT US

  • Netaji Subhash Place (NSP) Delhi
  • Tel: + (91) 8287315524
  • Email: contact@codewithcoffie.com

Copyright © 2026 LearnPress LMS | Powered by LearnPress LMS