forked from ManishK4514/Strivers-A2Z-DSA-Sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Intersection of Two Linked Lists.java
107 lines (101 loc) · 2.65 KB
/
Intersection of Two Linked Lists.java
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
// Solution 1: Time Complexity: O(N + M) & Space Complexity: O(N).
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
HashSet<ListNode> set = new HashSet<>();
while(headA != null){
set.add(headA);
headA = headA.next;
}
while(headB != null){
if(set.contains(headB)){
return headB;
}
headB = headB.next;
}
return null;
}
}
// Solution 2: Time Complexity: O(2N) & Space Complexity: O(1).
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == headB){
return headA;
}
int countA = 0;
int countB = 0;
ListNode dummyA = headA;
ListNode dummyB = headB;
while(dummyA != null || dummyB != null){
if(dummyA != null){
countA++;
dummyA = dummyA.next;
}
if(dummyB != null){
countB++;
dummyB = dummyB.next;
}
}
int temp = 0;
if(countA >= countB){
temp = countA - countB;
dummyA = headA;
dummyB= headB;
while(temp > 0){
dummyA = dummyA.next;
temp--;
}
}
else if(countB > countA){
temp = countB - countA;
dummyB = headB;
dummyA= headA;
while(temp > 0){
dummyB = dummyB.next;
temp--;
}
}
if(dummyA == dummyB){
return dummyA;
}
while(dummyA != null || dummyB != null){
if(dummyA != null){
countA++;
dummyA = dummyA.next;
}
if(dummyB != null){
countB++;
dummyB = dummyB.next;
}
if(dummyA == dummyB){
return dummyA;
}
}
return null;
}
}
// Solution 3: Time Complexity: O(2N) & Space Complexity: O(1).
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null){
return null;
}
ListNode a = headA;
ListNode b = headB;
while(a != b){
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
}