The problem is to find the intersection node of two singly linked lists. The intersection node is defined as the node that both linked lists share. If there is no intersection, return None
.
None
.None
.class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def getIntersectionNode(headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:
return None
def get_length(head):
length = 0
while head:
length += 1
head = head.next
return length
lenA = get_length(headA)
lenB = get_length(headB)
# Adjust head pointers to the same starting point
while lenA > lenB:
headA = headA.next
lenA -= 1
while lenB > lenA:
headB = headB.next
lenB -= 1
# Traverse both lists concurrently
while headA and headB:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
return None
O(N + M)
, where N
is the length of the first linked list and M
is the length of the second linked list.
O(N + M)
.O(N)
or O(M)
.O(min(N, M))
time.O(1)
, since we only use a constant amount of extra space.This approach ensures that no extra space is used, and it traverses each list only a limited number of times, providing an efficient solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?