[PYTHON] Let Code Day24 Starting from Zero "21. Merge Two Sorted Lists"

Overview

It seems that coding tests are conducted overseas in interviews with engineers, and in many cases, the main thing is to implement specific functions and classes according to the theme.

As a countermeasure, it seems that a site called Let Code will take measures.

A site that trains algorithmic power that can withstand coding tests that are often done in the home.

I think it's better to have the algorithm power of a human being, so I'll solve the problem irregularly and write down the method I thought at that time as a memo.

Leetcode

Leet Code Table of Contents Starting from Zero

Last time Leet Code Day 23 "226. Invert Binary Tree" starting from zero

Basically, I would like to solve the easy acceptance in descending order.

Twitter I'm doing it.

problem

21. Merge Two Sorted Lists

Given two sorted linked lists, merge them and return a new list.

Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

solution

I wanted to solve it using the iterative method, so this time I will post two methods, recursion and iterative method.

First is recursion.

# 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, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1 or not l2:
            return l1 or l2
        if l1.val >= l2.val:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2
        else:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
# Runtime: 32 ms, faster than 89.62% of Python3 online submissions for Merge Two Sorted Lists.
# Memory Usage: 13.8 MB, less than 6.61% of Python3 online submissions for Merge Two Sorted Lists.

I prefer recursion because it's simple and cohesive and very readable. It's also easier to write.

Next is an example of writing in the iterative method.

# 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, l1: ListNode, l2: ListNode) -> ListNode:
        temp = ans = ListNode(0)
        while l1 or l2:
            if l1 and l2:
                if l1.val < l2.val:
                    ans.next = l1
                    l1 = l1.next
                else:
                    ans.next = l2
                    l2 = l2.next
            elif l1:
                ans.next = l1
                l1 = l1.next
            elif l2:
                ans.next = l2
                l2 = l2.next
            ans = ans.next
        return temp.next

# Runtime: 28 ms, faster than 97.54% of Python3 online submissions for Merge Two Sorted Lists.
# Memory Usage: 13.9 MB, less than 6.61% of Python3 online submissions for Merge Two Sorted Lists.

The basic idea is to process by conditional branching while a specific element exists. In this example, processing is continued while l1 and l2 of ListNode exist, and if both exist, the values are compared and the smaller one is assigned to ʻans`, which is finally returned. This is how it is written because it is sufficient to move the element of ListNode that has no elements back by one.

This is easy for anyone to understand, but at the same time it feels a bit redundant. So I rewrote it.

# 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, l1: ListNode, l2: ListNode) -> ListNode:
        temp = ans = ListNode(0)
        while l1 and l2:
            if l1.val < l2.val:
                ans.next = l1
                l1 = l1.next
            else:
                ans.next = l2
                l2 = l2.next
            ans = ans.next
        ans.next = l1 or l2 
        return temp.next
# Runtime: 36 ms, faster than 70.49% of Python3 online submissions for Merge Two Sorted Lists.
# Memory Usage: 14 MB, less than 6.61% of Python3 online submissions for Merge Two Sorted Lists.

What has changed is that the condition of the while statement has changed from ʻor to ʻand, and with that change.

ans.next = l1 or l2

Is added. By doing this, the redundant part was greatly reduced. It will compare while both l1 and l2 are present, and if only one is present, it will substitute the rest in that order.

If there is a good answer, I will add it.

Recommended Posts

Let Code Day24 Starting from Zero "21. Merge Two Sorted Lists"
Let Code Day12 Starting from Zero "617. Merge Two Binary Trees"
Let Code Day92 Starting from Zero "4. Median of Two Sorted Arrays"
Let Code Day 35 "160. Intersection of Two Linked Lists" Starting from Zero
Let Code Day 42 "2. Add Two Numbers" Starting from Zero
Let Code Day48 Starting from Zero "26. Remove Duplicates from Sorted Array"
Let Code Day58 Starting from Zero "20. Valid Parentheses"
Let Code Day16 Starting from Zero "344. Reverse String"
Let Code Day49 starting from zero "1323. Maximum 69 Number"
Let Code Day89 "62. Unique Paths" Starting from Zero
Let Code Day 55 "22. Generate Parentheses" Starting from Zero
Let Code Day86 Starting from Zero "33. Search in Rotated Sorted Array"
Let Code Day18 starting from zero "53. Maximum Subarray"
Let Code Day 13 "338. Counting Bits" Starting from Zero
Let Code Day71 Starting from Zero "1496. Path Crossing"
Let Code Day 61 "7. Reverse Integer" starting from zero
Let Code Day 82 "392. Is Subsequence" Starting from Zero
Let Code Day51 Starting from Zero "647. Palindromic Substrings"
Let Code Day 50 "739. Daily Temperatures" Starting from Zero
Let Code Day 15 "283. Move Zeroes" starting from zero
Let Code Day14 starting from zero "136. Single Number"
Let Code Day 33 "1. Two Sum" starting from scratch
Let Code Day 43 "5. Longest Palindromic Substring" Starting from Zero
Let Code Day74 starting from zero "12. Integer to Roman"
Let Code Day57 Starting from Zero "35. Search Insert Position"
Let Code Day47 Starting from Zero "14. Longest Common Prefix"
Let Code Day78 Starting from Zero "206. Reverse Linked List"
Let Code Day52 Starting from Zero "1351. Count Negative Numbers in a Sorted Matrix"
Let Code Day 44 "543. Diameter of Binary Tree" starting from zero
Let Code Day 64 starting from zero "287. Find the Duplicate Number"
Let Code Day2 Starting from Zero "1108. Defanging an IP Address"
Let Code Day70 Starting from Zero "295. Find Median from Data Stream"
Let Code Day81 "347. Top K Frequent Elements" Starting from Zero
Let Code Day87 Starting from Zero "1512. Number of Good Pairs"
Let Code Day75 starting from scratch "15.3 Sum"
Let Code Day 29 "46. Permutations" starting from scratch
Let Code Day67 Starting from Zero "1486. XOR Operation in an Array"
Let Code Day56 Starting from Zero "5453. Running Sum of 1d Array"
Let Code Day7 starting from zero "104. Maximum Depth of Binary Tree"
Let Code Day5 starting from zero "1266. Minimum Time Visiting All Points"
Let Code Day83 Starting from Zero "102. Binary Tree Level Order Traversal"
Let Code Day 27 "101. Symmetric Tree" starting from scratch
Let Code Day 62 "83. Remove Duplicates from Sorted List"
Let Code Day 41 "394. Decode String" starting from scratch
Let Code Day 25 "70. Climbing Stairs" starting from scratch
Let Code Table of Contents Starting from Zero
Let Code Day69 starting from scratch "279. Perfect Squares"
Let Code Day 34 starting from scratch "118. Pascal's Triangle"
Let Code Day85 starting from scratch "6. ZigZag Conversion"
Let Code Day20 starting from scratch "134. Gas Station"
Let Code Day 88 "139. Word Break" starting from scratch
Let Code Day 28 "198. House Robber" starting from scratch
Let Code Day 39 "494. Target Sum" starting from scratch
Let Code Day 36 "155. Min Stack" starting from scratch
Let Code Day 17 "169. Majority Element" starting from scratch
Let Code Day 40 Starting from Zero "114. Flatten Binary Tree to Linked List"
Let Code Day59 starting from zero "1221. Split a String in Balanced Strings"
Let Code Day 11 Starting from Zero "1315. Sum of Nodes with Even-Valued Grandparent"
Let Code Day6 Starting from Zero "1342. Number of Steps to Reduce a Number to Zero"
Let Code Day 23 "226. Invert Binary Tree" starting from scratch
Let Code Day8 starting from scratch "1302. Deepest Leaves Sum"