LeetCode 160 – Python 3 (Week 3 – 01)

Solution 1

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        pointerA = headA
        pointerB = headB
        
        while pointerA != pointerB:
            if not pointerA:
                pointerA = headB
            else:
                pointerA = pointerA.next
            
            if not pointerB:
                pointerB = headA
            else:
                pointerB = pointerB.next
                
        return pointerA

Time complexity is O(m+n). Space complexity is O(1).

Leave a comment

Design a site like this with WordPress.com
Get started