【Fixed】Python accepted solution before now causes Memory Limit Exceeded


  • 6

    I have resolved this problem several months ago. But now when I submit the same code, it always get MLE. I also tried other solutions posted in the discuss, still got MLE. @StefanPochmann

    Update: Many thanks to @skyeyvapor, it's accepted when add gc.collect() manually. I already updated the codes below.

    This is my solution.

    import gc
    
    class Solution(object):
        def cout(self, head):
            cnt = 0
            while head:
                cnt += 1
                head = head.next
    
            # manually clean the memory
            gc.collect()
            return cnt
    
        def getIntersectionNode(self, headA, headB):
            l1, l2, cnt1, cnt2 = headA, headB, self.cout(headA), self.cout(headB)
            if cnt2 > cnt1:
                l1, l2 = l2, l1
    
            for _ in range(abs(cnt1 - cnt2)):
                l1 = l1.next
    
            while l1:
                if l1 is l2:
                    return l1
    
                l1, l2 = l1.next, l2.next
    

    And this is another solution I tried.

    import gc
    
    class Solution(object):
        def getIntersectionNode(self, headA, headB):
            a, b = headA, headB
            while a is not b:
                a = headB if a is None else a.next
                b = headA if b is None else b.next
            
            # clean the memory
            gc.collect()
            return a
    

  • 0
    C

    I got the same problem.


  • 1
    S

    It seems like LeetCode added a big no intersection test case.
    Used gc.collect() after pointer_a first hit the end to pass MLE.


  • 0

    @skyeyvapor Yeah, you are right! It's accepted after I add gc.collect(), thanks!


  • 0
    R

    I like your second solution. You are so smart!


Log in to reply
 

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