[Python] Time Limit Exceeded

  • 0

    Hi all,

    I met the "Time Limit Exceeded" on the following case. But I have no idea about how to reduce my code. Can you kindly give me some suggestion? thanks! :)

    Last executed input: {1,2,3}, 2, 3

    My code:

    def reverseBetween(self, head, m, n):
        cur = head
        prev = None
        orig_prev = None
        start_m = None
        idx = 1
        if m > n:
            return None
        if m==n:
            return head
        if m==1:
            orig_prev = head
            start_m = head
        while cur.next != None:
            if idx < m:
                # do nothing
            elif m == (idx + 1):
                # prepare to reverse the link list node
                orig_prev = cur
                # start index of reverse link list
                start_m = cur.next
            elif m < idx <= n:
                # reverse the link list node
                if idx == n:
                    #update the head/tail node of reversed link list
                    orig_prev.next = cur
                    start_m.next = cur.next
                # step 1: tmp = next
                tmp = cur.next
                #step 2: cur.next = prev
                cur.next = prev
            if idx == n:
                #update the prev and cur
                prev = cur
                cur = cur.next
        return head

Log in to reply

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