Weekly Coding Challenge – Merge Two Sorted Lists – written in Python3

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 the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []
Output: []

Example 3:

Input: list1 = [], list2 = [0]
Output: [0]

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        first_lst = []
        sec_lst = []
        if list1:
            first_lst = self.lstNodeToArr(list1, [])
        if list2:
            sec_lst = self.lstNodeToArr(list2, [])
        fin_arr = first_lst + sec_lst
        fin_arr.sort()
        fin_arr.reverse()
        return self.arrToListNode(fin_arr)
        
    def lstNodeToArr(self, lstNode, finlst):
        if lstNode.next:
            finlst.append(lstNode.val)
            return self.lstNodeToArr(lstNode.next, finlst)
        else:
            finlst.append(lstNode.val)
            return finlst
    
    def arrToListNode(self, lst):
        nodeList = None
        for x in lst:
            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