Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

160. Intersection of Two Linked Lists

Explanation

To find the intersection point of two linked lists, we can use a two-pointer approach. We start by iterating through both lists simultaneously using two pointers, one for each list. When a pointer reaches the end of a list, we reset it to the head of the other list. This way, the pointers will travel the same distance before reaching the intersection point.

If the lists intersect, the pointers will meet at the intersection node. If the lists do not intersect, both pointers will reach the end simultaneously, indicating no intersection.

This approach has a time complexity of O(m + n) and uses only O(1) additional memory.

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pA = headA;
        ListNode pB = headB;

        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }

        return pA;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.