<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: H. M. Jabed Omur Rifat</title>
    <description>The latest articles on DEV Community by H. M. Jabed Omur Rifat (@h_mjabedomurrifat_2b).</description>
    <link>https://dev.to/h_mjabedomurrifat_2b</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3500807%2F675ad599-8dd8-4b2c-9796-d41b6ff1412b.jpg</url>
      <title>DEV Community: H. M. Jabed Omur Rifat</title>
      <link>https://dev.to/h_mjabedomurrifat_2b</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/h_mjabedomurrifat_2b"/>
    <language>en</language>
    <item>
      <title>Solving LeetCode's "Add Two Numbers" Iteratively and Recursively - Part 1</title>
      <dc:creator>H. M. Jabed Omur Rifat</dc:creator>
      <pubDate>Sun, 14 Sep 2025 12:59:18 +0000</pubDate>
      <link>https://dev.to/h_mjabedomurrifat_2b/solving-leetcodes-add-two-numbers-iteratively-and-recursively-part-1-41j5</link>
      <guid>https://dev.to/h_mjabedomurrifat_2b/solving-leetcodes-add-two-numbers-iteratively-and-recursively-part-1-41j5</guid>
      <description>&lt;p&gt;If you’ve spent any time preparing for software engineering interviews, you’ve likely come across LeetCode's &lt;strong&gt;&lt;a href="https://leetcode.com/problems/add-two-numbers?envType=problem-list-v2&amp;amp;envId=recursion" rel="noopener noreferrer"&gt;Add Two Numbers.&lt;/a&gt;&lt;/strong&gt; This problem is a classic, frequently asked by top tech companies because it’s a perfect test of your understanding of recursion, linked lists and basic arithmetic logic.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fztztg9e9pv7wohtm3y8t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fztztg9e9pv7wohtm3y8t.png" alt=" " width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this article, we’ll break down this problem step-by-step. We won't just look at one solution, but two powerful approaches: a straightforward iterative method and an elegant recursive one.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Breaking Down the Problem&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;First, let's understand the task. We are given two non-empty linked lists, where each node contains a single digit. The digits are stored in reverse order. Our job is to add the two numbers together and return the result as a new linked list.&lt;/p&gt;

&lt;p&gt;For example, if the inputs are &lt;code&gt;l1 = [2,4,3]&lt;/code&gt; and &lt;code&gt;l2 = [5,6,4]&lt;/code&gt;, this represents the numbers 342 and 465. The sum is 807, which should be returned as the linked list &lt;code&gt;[7,0,8]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The key insight here is that the &lt;strong&gt;reverse order&lt;/strong&gt; makes our job much easier. It mimics how we do addition by hand—starting from the rightmost digit and moving left, keeping track of a carry value.&lt;/p&gt;

&lt;p&gt;So, the core challenges are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Traverse both linked lists simultaneously.&lt;/li&gt;
&lt;li&gt;Handle cases where one list is longer than the other.&lt;/li&gt;
&lt;li&gt;Correctly calculate and manage the carry at each step.&lt;/li&gt;
&lt;li&gt;Construct the new result linked list as we go.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Solution 1: The Iterative Approach (The Workhorse)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The most direct way to solve this is with a &lt;code&gt;while&lt;/code&gt; loop. We'll iterate through the lists as long as there are digits left in either &lt;code&gt;l1&lt;/code&gt; or &lt;code&gt;l2&lt;/code&gt;, or if there's a &lt;code&gt;carry&lt;/code&gt; left over from the last calculation.&lt;/p&gt;

&lt;p&gt;A common and very useful pattern here is to use a &lt;code&gt;dummyNode&lt;/code&gt;. This node acts as a placeholder for the head of our new list, simplifying the code so we don't have to handle the first node as a special case.&lt;/p&gt;

&lt;p&gt;Here is the complete iterative solution in Python:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution(object):
    def addTwoNumbers(self, l1, l2):
        dummyNode = ListNode(0)
        current = dummyNode
        carry = 0

        while l1 or l2 or carry != 0:
            # Get the values, using 0 if a list is exhausted
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0

            # Perform the addition
            total_sum = val1 + val2 + carry
            carry = total_sum // 10
            digit = total_sum % 10

            # Create the new node and advance our pointer
            current.next = ListNode(digit)
            current = current.next

            # Advance the list pointers
            if l1: l1 = l1.next
            if l2: l2 = l2.next

        return dummyNode.next
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Here is the explanation of iterative solution:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; We create a &lt;code&gt;dummyNode&lt;/code&gt; to anchor our result list and a &lt;code&gt;current&lt;/code&gt; pointer to build it. &lt;code&gt;carry&lt;/code&gt; starts at 0.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The Loop:&lt;/strong&gt; The &lt;code&gt;loop&lt;/code&gt; continues as long as &lt;code&gt;l1&lt;/code&gt;, &lt;code&gt;l2&lt;/code&gt;, or &lt;code&gt;carry&lt;/code&gt; has a value. This elegantly handles different list lengths and the final carry (like in &lt;code&gt;9 + 9 = 18&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frtblyuzadvx7ivn3tvtw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frtblyuzadvx7ivn3tvtw.png" alt=" " width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Value Extraction:&lt;/strong&gt; &lt;code&gt;val1 = l1.val if l1 else 0&lt;/code&gt; is a clean way to handle one list being longer than the other. If a list is &lt;code&gt;None&lt;/code&gt;, we just use 0 for the calculation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Building the Result:&lt;/strong&gt; We create a new &lt;code&gt;ListNode&lt;/code&gt; with the calculated &lt;code&gt;digit&lt;/code&gt; and attach it to our result list.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Return Value:&lt;/strong&gt; We return &lt;code&gt;dummyNode.next&lt;/code&gt;, which is the true head of our new list.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Solution 2: The Recursive Approach (The Elegant Alternative)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Recursion can often lead to more concise and declarative code. The problem can be rephrased recursively:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The sum of two linked lists is a new node with the sum of the current digits, whose next pointer is the sum of the rest of the lists.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This maps perfectly to a recursive function.&lt;/p&gt;

&lt;p&gt;Here is the recursive solution:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution(object):
    def addTwoNumbers(self, l1, l2, carry=0):
        # Base Case: stop when there are no more nodes and no carry
        if not l1 and not l2 and not carry:
            return None

        # Get the values, using 0 if a node is None
        val1 = l1.val if l1 else 0
        val2 = l2.val if l2 else 0

        # Perform the addition
        total_sum = val1 + val2 + carry
        carry = total_sum // 10
        digit = total_sum % 10

        # Create the new node for the current digit
        newNode = ListNode(digit)

        # Recursive Step: call the function for the next nodes
        next_l1 = l1.next if l1 else None
        next_l2 = l2.next if l2 else None
        newNode.next = self.addTwoNumbers(next_l1, next_l2, carry)

        return newNode
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Here is the explanation of recursive solution:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Base Case:&lt;/strong&gt; The recursion stops when both lists are exhausted (&lt;code&gt;None&lt;/code&gt;) and there is no &lt;code&gt;carry&lt;/code&gt; left to add. This is the most crucial part of any recursive solution.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgrxpgo55v4ooqxyc0gxr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgrxpgo55v4ooqxyc0gxr.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Recursive Step:&lt;/strong&gt; For the current call, we calculate the &lt;strong&gt;sum&lt;/strong&gt; and &lt;strong&gt;digit&lt;/strong&gt; just like in the iterative version. We create a &lt;strong&gt;newNode&lt;/strong&gt; with this digit. The magic happens next: we set &lt;strong&gt;newNode.next&lt;/strong&gt; to the result of calling the function again with the next nodes and the new &lt;code&gt;carry&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Comparing the Approaches&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Time Complexity&lt;/strong&gt; is the &lt;strong&gt;same(O(n))&lt;/strong&gt; for both because we must visit each node in the longer list at least once.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5rebxp0096pxx6d7p4o6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5rebxp0096pxx6d7p4o6.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity&lt;/strong&gt; is the key difference. The iterative solution uses a &lt;strong&gt;constant(O(1))&lt;/strong&gt; amount of extra space for the &lt;code&gt;dummyNode&lt;/code&gt;, &lt;code&gt;current&lt;/code&gt;, and &lt;code&gt;carry&lt;/code&gt; variables. The recursive solution, however, creates a new stack frame for each call, so the &lt;strong&gt;space(O(n))&lt;/strong&gt; it uses is &lt;strong&gt;proportional&lt;/strong&gt; to the length of the longest list. For very large lists, this could theoretically lead to a stack overflow error.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;Add Two Numbers&lt;/strong&gt; problem is a fantastic exercise for mastering &lt;strong&gt;recursion&lt;/strong&gt; and &lt;strong&gt;linked list&lt;/strong&gt; manipulation. By implementing both an iterative and a recursive solution, we can appreciate the different ways to approach the same problem and understand their unique trade-offs in terms of space and readability.&lt;/p&gt;

&lt;p&gt;Which solution do you prefer? Let me know in the comments! Happy coding.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>recursion</category>
      <category>python</category>
      <category>linkedlist</category>
    </item>
  </channel>
</rss>
