LeetCode - Intersection Of Two Linked Lists

1 minute read

Problem description

description

intersection-of-two-linked-lists

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

Analysis

The first thought is to use a HashSet to store every node have seen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
 * 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) {
        HashSet<ListNode> set = new HashSet<>();
        
        ListNode p1 = headA;
        ListNode p2 = headB;
        
        while (p1 != null || p2 != null){
            if (p1 == null){
                if(set.contains(p2)){
                    return p2;
                }
                
                set.add(p2);
                
                p2 = p2.next;
            }
            else if (p2 == null){
                if (set.contains(p1)){
                    return p1;
                }
                
                set.add(p1);
                
                p1 = p1.next;
            }
            else{
                if (set.contains(p1)){
                    return p1;
                }
                set.add(p1);
                
                p1 = p1.next;
                
                
                if (set.contains(p2)){
                    return p2;
                }
                set.add(p2);
                
                p2 = p2.next;
            }
        }
        
        return null;
    }
}

However, there’s a better solution from LeetCode, we can start from the head of another list if we reach the end.

Suppose we have two lists, and the common part is marked as C. Then we have:

A - C - B - C

B - C - A - C

So that we can know that the first intersection one is the C.

1
2
3
4
5
6
7
8
9
10
11
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        
      ListNode pa = headA, pb = headB;
        while (pa != pb) {
            pa = (pa != null) ? pa.next : headB;
            pb = (pb != null) ? pb.next : headA;
        }
        return pa;
        
        
    }

What to improve

  • we can use the observation to check intersection in O(1) SC.