getIntersectionNodeWithHashSet<T> function
LinkedListNode<T> ?
getIntersectionNodeWithHashSet<T>(
- LinkedListNode<
T> ? headA, - LinkedListNode<
T> ? headB
Finds the intersection point using hash set approach
headA - The head of the first linked list
headB - The head of the second linked list
Returns the intersection node, or null if no intersection exists
Time Complexity: O(n + m) where n and m are the lengths of the lists Space Complexity: O(n) due to hash set usage
Implementation
LinkedListNode<T>? getIntersectionNodeWithHashSet<T>(
LinkedListNode<T>? headA,
LinkedListNode<T>? headB,
) {
if (headA == null || headB == null) return null;
Set<LinkedListNode<T>> visited = {};
LinkedListNode<T>? current = headA;
// Add all nodes from first list to set
while (current != null) {
visited.add(current);
current = current.next;
}
// Check second list for intersection
current = headB;
while (current != null) {
if (visited.contains(current)) {
return current;
}
current = current.next;
}
return null;
}