700163. Intersection in Y Shaped Lists
Intersection in Y Shaped Lists
Summary
The problem is about finding the intersection point between two linked lists that form a Y shape. The linked lists are represented as nodes with values and pointers to the next node. The goal is to find the common node shared by both lists.
Detailed Explanation
To solve this problem, we can use a simple iterative approach. We start by traversing one of the linked lists until we reach the end. Then, we traverse the other list while comparing nodes with the first list. If we find a match, that's the intersection point. Here's a step-by-step breakdown:
- Initialize two pointers,
p1andp2, to the start of each linked list. - Traverse the first list until you reach the end (
nullorNone). - Then, traverse the second list while comparing nodes with the first list using the following steps:
- If the current node in the second list matches the current node in the first list, return that node as the intersection point.
- If not, move to the next node in the second list and repeat step 3.
- If you reach the end of both lists without finding a match, there is no intersection.
Time Complexity: O(max(m, n), where m and n are the lengths of the two linked lists.
Space Complexity: O(1) since we only use a few extra variables to store the pointers.
Here's an ASCII art diagram to illustrate the Y shape:
A -> B -> C
| |
D -> E
In this example, node C is the intersection point between the two linked lists.
Optimized Solutions
Java
public Node findIntersection(Node head1, Node head2) {
Node p1 = head1;
while (p1.next != null) {
p1 = p1.next;
}
Node p2 = head2;
while (p2.next != null || p1 == p2) {
p2 = p2.next;
}
if (p1 == p2) return p1; // intersection point found
return null; // no intersection
}