Akarshan's | Blog

Every Developers Journey is unique. Here's mine.

Leetcode - 2. Add Two Numbers

Akarshan MishraAkarshan Mishra

Recursion

Linked List

Leetcode - 2. Add Two Numbers Image
July 27, 2023
A detailed explanation and solution to LeetCode problem 2: Add Two Numbers. Learn how to solve this linked list problem using recursion.

The Problem:

In this problem, we are given two non-empty linked lists that represent two positive integers. Our goal is to reverse both linked lists, find their sum, and return it as a reversed linked list.

Before we begin trying to figure out a solution for this problem, let’s first revisit an important concepts Linked List and Recursion.

Understanding Recursion:

Recursion is essentially a function calling itself. It is frequently used to solve problems that can be divided into smaller, similar sub-problems and can be very useful in dynamic programming. To understand recursion, it can be helpful to break it down into 3 parts:

  1. Base Condition: This condition prevents the recursive function from calling itself infinitely.
  2. Recursive Call: This is responsible for calling the recursive function itself.
  3. Small Calculation: This step, which can come before or after the Recursive Call, is responsible for performing some calculation that we need for the recursive function or for returning some result after a recursive call has been completed.

A recursive tree is a visual representation of the recursive calls made by a function. It can be very helpful in understanding how recursion works and in analyzing the time and space complexity of recursive algorithms.

Understanding Linked List:

A linked list is a linear data structure that consists of a sequence of nodes, each containing data and a reference to the next node in the list. It is often used as an alternative to arrays, as it can be more efficient in certain operations such as insertion and deletion.

To understand linked lists, it can be helpful to break it down into 3 parts:

  1. Nodes: Each node in a linked list contains some data and a reference to the next node in the list.
  2. Head: The head of a linked list is the first node in the list. It is used as the starting point for many operations on the list.
  3. Traversal: Traversing a linked list involves starting at the head and following the references from one node to the next until the desired node is reached or the end of the list is reached.

Linked lists can be very useful in solving problems that involve dynamic data structures, as they allow for efficient insertion and deletion of elements. They can also be used in combination with other data structures, such as stacks and queues, to solve more complex problems.

Intuition:

With an understanding of how recursion and linked lists work, let’s try to break down the problem. We don't have to worry about making our own linked list data structure as it is given. From the problem statement we can deduce that that we might need a function to extract the numbers in reverse from the linked list, as shown in the image below.

LeetCode-2 Diagram 1

After both the numbers have been extracted then we can add them and reverse the digits, this can also be done by a recursive function, as shown in the image below.

LeetCode-2 Diagram 2

At last, we can have a function that converts strings back to linked list.

Summary of Solution

Use recursion to extract the numbers from the linked lists in reverse. Add the extracted numbers and reverse the result. Convert the result back into a linked list. The solution makes use of important concepts such as linked lists and recursion.

Code

This can be translated to code in the following way:

Solution.py

lang: python

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
def reverse(node, val):
if node.next is None:
val += str(node.val)
return val
val = reverse(node.next, val)
val += str(node.val)
return val
def reverseString(s, start, end):
if start >= end:
return s
s = list(s)
s[start], s[end] = s[end], s[start]
s = ''.join(s)
return reverseString(s, start + 1, end - 1)
def makeLinkedList(s):
# Create a dummy node to serve as the head of the linked list
dummy = ListNode()
current = dummy
for ch in s:
n = ListNode(int(ch))
current.next = n
# Move to the next node
current = current.next
return dummy.next
num1 = int(reverse(l1, ""))
num2 = int(reverse(l2, ""))
sumN = str(num1+num2)
sumN = reverseString(sumN,0, len(sumN) - 1)
return makeLinkedList(sumN)
  • Time Complexity O(max(n,m))
  • Space Complexity O(max(n,m))

The time complexity of this solution is O(max(n, m)), where n and m are the lengths of the two input linked lists. This is because the function needs to traverse both linked lists to extract the numbers, and the time it takes to do so is proportional to the length of the longer linked list.

This approach is simple and efficient, making it a good solution to this problem.

I hope you enjoyed this post. Stay tuned for daily LeetCode blog posts!

Latest Posts

Leetcode - 21. Merge Two Sorted Lists
Akarshan MishraAkarshan Mishra

Recursion

Linked List

Leetcode - 21. Merge Two Sorted Lists

August 14, 2023

A detailed explanation and solution to LeetCode problem 21: Merge Two Sorted Lists. Learn how to solve this linked list problem using recursion.

Leetcode - 138. Copy List with Random Pointer
Akarshan MishraAkarshan Mishra

Recursion

Linked List

Leetcode - 138. Copy List with Random Pointer

August 12, 2023

A detailed explanation and solution to LeetCode problem 138: Copy List with Random Pointer. Learn how to solve this linked list problem using recursion.