LeetCode – Intersection of Two Linked Lists (Java)

Problem

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

```A:          a1 -> a2
->
c1 -> c2 -> c3
->
B:     b1 -> b2 -> b3
```

begin to intersect at node c1.

Java Solution

First calculate the length of two lists and find the difference. Then start from the longer list at the diff offset, iterate though 2 lists and find the node.

```/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int len1 = 0; int len2 = 0; ListNode p1=headA, p2=headB; if (p1 == null || p2 == null) return null;   while(p1 != null){ len1++; p1 = p1.next; } while(p2 !=null){ len2++; p2 = p2.next; }   int diff = 0; p1=headA; p2=headB;   if(len1 > len2){ diff = len1-len2; int i=0; while(i<diff){ p1 = p1.next; i++; } }else{ diff = len2-len1; int i=0; while(i<diff){ p2 = p2.next; i++; } }   while(p1 != null && p2 != null){ if(p1.val == p2.val){ return p1; } p1 = p1.next; p2 = p2.next; }   return null; } }```
Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• SM TechWorld

Multiple Approaches, Simple Explanation.
https://youtu.be/e3G3oytMVXY

• Alik Elzin

I think I have a much nicer solution.
1. If we use short/long lists, we don’t need to duplicate the list shortening loop.
2. If both lists have the same length, comparing one against the other is good enough, as eventually, `null == null`.

``` Node findIntersection(Node l1, Node l2) { if (l1 == null || l2 == null) return null;```

``` int len1 = length(l1); int len2 = length(l2); Node short = len1 > len2 ? l2 : l1; Node long = len1 <= len2 ? l2 : l1; for (int i = 0 ; i < Math.abs(len1-len2) ; i++) { long = long.next; } while (long != short) { long = long.next; short = short.next; } return long; /*Can be `short` as well. Same value.*/ } int length(Node n) { int len = 0; for (Node n = l1 ; n != null ; n = n.next) { len++; } ```

``` return len; } ```

• Alik Elzin

The presented solution first traverses over all elements of both lists.
But what if the lists are very long and the intersection point is at the beginning?
An O(n1+n2) space solution would be to save elements of both lists as we go (HashSet) until we find one that is on the other list.
Though this solution is the same O(k1+k2) compute time as the presented solution, it can perform faster in a lot of cases but almost non slower.

• vishesh jain

After watching this video I solved this problem in very unique way and there is very interesting twist in the video as well . https://www.youtube.com/watch?v=xnmbO3lxhRM .
Explained really well step by step till the last. Do watch if you are struggling hard. This question seems easy but its modified version is not that much if you don’t know the technique .

• Davis Benny

Life Saver Video !!! I was able to solve the problem in 5 minutes with O(n+m) complexity

https://youtu.be/mkgv7ns_y6I

Thank you.Highly recommended to all my friends.

• Suresh Tathari

Needs update in the last check to cover all the conditions

while(p1 != null && p2 != null){
if(p1 == p2)
return p1;
p1 = p1.next;
p2 = p2.next;

}

• Narendra

thanks dude!

• Mayank Mittal

We can also solve it in O(m+n) using hashSet:

```>public ListNode solution2(ListNode list1, ListNode list2) { Set set = new HashSet();```

``` ListNode n1Current = list1; while(n1Current != null){ set.add(n1Current); n1Current = n1Current.next; } ListNode n2Current = list2; while(n2Current != null){ if(set.contains(n2Current)){ return n2Current; } n2Current = n2Current.next; } ```

``` return null; }```

• Udaydeep Thota

// Time Complexity: O(elements in first list + elements in second list)
// Space Complexity: O(elements in first list)
public Node intersectionNodeInList(Node head1, Node head2) {

return null;

HashSet nodeStoreSet = new HashSet();
Node current1 = head1;
Node current2 = head2;

while(current1!=null) {

current1=current1.next;

}

while(current2!=null) {

if(nodeStoreSet.contains(current2))
return current2;
current2=current2.next;
}

return null;

}

• ramkrishna

p1.val==p2.val is incorrect as doesn’t compare the all the nodes next to it.
It only compares with two nodes.Replace it with p1==p2
ex:
56 79 78 13 97 64 47 20 80 85
97 6 46 83 54 47 20 81 85
It will give ans 47 20 80 85
But correct ans is 85

• Ayush

if space is not an issue put both in stack ..then pop can compare til both are same.

• Sitian Liu

The last while loop only works if the lists are the same length. The goal is to start at a point on both list where they have even number of elements left

• Sitian Liu

What if you aren’t allowed to modify the lists and want to keep the space down to O(1)?

• Anand Varma

Reverse both the lists and iterate the reversed lists as long as the nodes are the same. When the nodes differ, the element before that is the intersection point.

• Anup

Also assignments:

are done twice unnecessarily.

BTW, thanks for the program, programcreek 🙂

• George

Agree!!

• disqus_NInBSQ2Jb7

the last while loop is fine ..i dont understand the need to calculate difference and moving pointers

• Shawn

I think we should not do if(p1.val == p2.val){, but just if (p1 == p2)..