Weekly Coding Challenge: Add Two Numbers – written in python

Posted by

Hello readers! It’s really important for me to continue my practice and learning. Every week, I block off 30 minutes, set a timer and choose a challenge from leetcode. This helps me keep my skills sharp, see how other devs all over the planet would solve these problems, and take some leisure time to problem solve and be creative. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. Today, the problem set focuses on Python.

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 contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

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

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]


  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        l1numb = self.convertNumb(self.lstNodeToArr(l1, []))
        l2numb = self.convertNumb(self.lstNodeToArr(l2, []))
        return self.arrToListNode([int(i) for i in str(l1numb + l2numb)])
    def lstNodeToArr(self, lstNode, finlst):
        if lstNode.next:
            return self.lstNodeToArr(lstNode.next, finlst)
            return finlst
    def convertNumb(self, lst):
        strings = [str(integer) for integer in lst]
        a_string = "". join(strings)
        return int(a_string)
    def arrToListNode(self, numbs):
        nodeList = None
        for x in numbs:
            nodeList = ListNode(x, next=nodeList)
        return nodeList

All solutions are also now on my GitHub profile if you want to check out all of the coding challenges I’ve completed so far!

All credit to problem sets goes to Leetcode

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s