shlogg · Early preview
Prashant Mishra @prashantrmishra

Finding Intersection Node In LinkedLists With O(N+M) Time Complexity

Find intersection of two LinkedLists by getting length difference, traveling ahead in longest list & returning when same nodes are encountered.

Problem

  
  
   Brute force approach:

Time complexity: O(N+M) where N and M are length of two LinkedLists given.

  
  
  Intuition

Find length of both the nodes and get the length difference
Travel ahead in the longest list by length difference of both the lists, by this both the lists will start from the same length.
return when same nodes are encountered.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListN...