Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion linked_lists/intersection.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,26 @@ def intersection_node(headA, headB):
""" Will return the node at which the two lists intersect.
If the two linked lists have no intersection at all, return None.
"""
pass

'''
The algorithm is: Hashset
1.Store all the elements of headA in a hashset
2.Iterate through the headB and check for the first match and then return it.
Time Complexity - O(n+m)
Space Complexity - O(n)
'''
first_set = set()
curr = headA

while curr:
first_set.add(curr)
curr = curr.next

curr = headB
while curr:
if curr in first_set:
return curr
curr = curr.next

return None