LeetCode 160: Intersection of Two Linked Lists Solution

Master LeetCode problem 160 (Intersection of Two Linked Lists), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

160. Intersection of Two Linked Lists

Problem Explanation

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.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 160 (Intersection of Two Linked Lists)?

This page provides optimized solutions for LeetCode problem 160 (Intersection of Two Linked Lists) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 160 (Intersection of Two Linked Lists)?

The time complexity for LeetCode 160 (Intersection of Two Linked Lists) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 160 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 160 in Java, C++, or Python.

Back to LeetCode Solutions