Time Limit Exceeded for Correct Python Solution

  • 0
    class Solution:
        def sortList(self, head):
            def mergeSort(head):
                left = head
                if left is None or left.next is None:
                    return left
                right = split(left)
                left = mergeSort(left)
                right = mergeSort(right)
                return merge(left, right)
            def split(head):
                if head is None or head.next is None:
                slow = head
                fast = head.next
                while fast is not None and fast.next is not None:
                    slow = slow.next
                    fast = fast.next.next
                right = slow.next
                slow.next = None
                return right
            def merge(left, right):
                head = Node(0)
                curr = head
                while left != None and right != None:
                    if left.val <= right.val:
                        curr.next = left
                        left = left.next
                        curr.next = right
                        right = right.next
                    curr = curr.next
                if left != None:
                    curr.next = left
                if right != None:
                    curr.next = right
                return head.next
            return mergeSort(head)

  • 0

    Where could I speed things up?

  • 0

    Questions about code you've written must describe the specific problem clearly, elaborate thoughts based on code. Please read the Discus FAQ for more info.

  • 0

    Yeah I can testify that correct Python solution gets TLE... Our solutions are about the same.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.