Skip to content

Commit 2732492

Browse files
author
Joseph Luce
authored
Create 160_intersection_of_two_linked_lists.md
1 parent 082fbd0 commit 2732492

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# 160. Intersection of Two Linked Lists
2+
3+
## Solution with dictionary
4+
- Runtime: O(N)
5+
- Space: O(1)
6+
- N = Number of nodes in linked list
7+
8+
If you first count the amount of nodes in both linked list, you can then figure out the difference in the number of nodes between the two.
9+
Using that, you can then move the starting pointer of the longest linked list to the position where you can iterate both linked lists at the same time to find the intersection node.
10+
11+
```
12+
class Solution(object):
13+
def getIntersectionNode(self, headA, headB):
14+
"""
15+
:type head1, head1: ListNode
16+
:rtype: ListNode
17+
"""
18+
def get_n_nodes(root):
19+
if root is None:
20+
return 0
21+
n_nodes = 1
22+
while root is not None:
23+
root = root.next
24+
n_nodes += 1
25+
return n_nodes
26+
27+
if headA is None or headB is None:
28+
return None
29+
n_A_nodes = get_n_nodes(headA)
30+
n_B_nodes = get_n_nodes(headB)
31+
n_diff_nodes = abs(n_A_nodes - n_B_nodes)
32+
if n_A_nodes < n_B_nodes: # headA is longest
33+
headA, headB = headB, headA
34+
for _ in range(n_diff_nodes):
35+
headA = headA.next
36+
while headA and headB:
37+
if headA is headB:
38+
return headA
39+
headA = headA.next
40+
headB = headB.next
41+
return None
42+
```

0 commit comments

Comments
 (0)