Intersection of Two Linked Lists – Leetcode Solution

In this post, we are going to solve the 160. Intersection of Two Linked Lists problem of Leetcode. This problem 160. Intersection of Two Linked Lists is a Leetcode easy level problem. Let’s see code, 160. Intersection of Two Linked Lists – Leetcode Solution.

Problem

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

For example, the following two linked lists begin to intersect at node c1:

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

Note that the linked lists must retain their original structure after the function returns.

Custom Judge:

The inputs to the judge are given as follows (your program is not given these inputs):

  • intersectVal – The value of the node where the intersection occurs. This is 0 if there is no intersected node.
  • listA – The first linked list.
  • listB – The second linked list.
  • skipA – The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.
  • skipB – The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.

The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.

Example 1 :


Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.

Example 2 :


Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.

Example 3 :


Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: No intersection
Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.

Constraints

  • The number of nodes of listA is in the m.
  • The number of nodes of listB is in the n.
  • 1 <= m, n <= 3 * 104
  • 1 <= Node.val <= 105
  • 0 <= skipA < m
  • 0 <= skipB < n
  • intersectVal is 0 if listA and listB do not intersect.
  • intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.

Now, let’s see the code of 160. Intersection of Two Linked Lists – Leetcode Solution.

Intersection of Two Linked Lists – Leetcode Solution

160. Intersection of Two Linked Lists – Solution in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    public int length(ListNode node){
        
        ListNode curr = node;
        int len=0;
        while(curr != null){
            curr = curr.next;
            len++;
        }
        return len;
        
    }
    
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        
        ListNode A = headA;
        ListNode B = headB;
        
        int lenA = length(A);
        int lenB = length(B);
        
        int diff = Math.abs(lenA-lenB);
        
        ListNode longestList = lenA > lenB? A : B;
        
        while(diff-- > 0){
            
            longestList = longestList.next;
            
        }
        
        ListNode curr = lenA > lenB ? B : A;
        while(curr!= null && longestList != null){
            if(curr == longestList) return curr;
            curr = curr.next;
            longestList = longestList.next;
        }
        
        return null;
    }
}

160. Intersection of Two Linked Lists – Solution in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int cnt1 = 0;
        int cnt2 = 0;
        ListNode* l1 = headA;
        ListNode* l2 = headB;
        while(l1){
            cnt1++;
            l1 = l1->next;
        }
        while(l2){
            cnt2++;
            l2 = l2->next;
        }
        l1 = headA;
        l2 = headB;
        if(cnt1>cnt2){
            int dif = cnt1 - cnt2;
            while(dif){
                l1 = l1->next;
                dif--;
            }
        }
        if(cnt2>cnt1){
            int dif = cnt2 - cnt1;
            while(dif){
                l2 = l2->next;
                dif--;
            }
        }
        while((l1&&l2)&&(l1!=l2)){
            l1 = l1->next;
            l2 = l2->next;
        }
        return l1;
    }
};

160. Intersection of Two Linked Lists – Solution in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, a: ListNode, b: ListNode) -> Optional[ListNode]:
        alen = self.getLength(a)
        blen = self.getLength(b)
        
        if alen < blen:
            alen, blen = blen, alen
            a, b = b, a
            
        diff = alen - blen
        for _ in range(diff):
            a = a.next
            
        while a and b:
            if a is b:
                return a
            
            a = a.next
            b = b.next        
        
        return None
        
    def getLength(self, head):
        count = 0
        
        while head:
            count += 1
            head = head.next
        
        return count
        

Note: This problem 160. Intersection of Two Linked Lists is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *