Skip to content

Commit a2ff672

Browse files
committed
O(n) time and O(1) space
1 parent 1ef7050 commit a2ff672

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Write a program to find the node at which the intersection of two singly linked lists begins.
3+
4+
For example, the following two linked lists:
5+
6+
7+
begin to intersect at node c1.
8+
9+
10+
11+
Example 1:
12+
13+
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
14+
Output: Reference of the node with value = 8
15+
Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
16+
"""
17+
# Definition for singly-linked list.
18+
# class ListNode:
19+
# def __init__(self, x):
20+
# self.val = x
21+
# self.next = None
22+
23+
class Solution:
24+
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
25+
a,b = headA,headB
26+
lenA,lenB = 0,0
27+
while a:
28+
lenA += 1
29+
a = a.next
30+
while b:
31+
lenB += 1
32+
b = b.next
33+
a,b = headA,headB
34+
if lenA > lenB:
35+
for i in range(lenA-lenB):
36+
a = a.next
37+
elif lenB > lenA:
38+
for i in range(lenB-lenA):
39+
b = b.next
40+
while a != b:
41+
a = a.next
42+
b = b.next
43+
return b

0 commit comments

Comments
 (0)