Algorithm-Day22-Intersection-of-Two-Linked-Lists-lc-160
🧩 Problem Description
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
.
The linked lists must retain their original structure after the function returns.
Example:
1 | Input: |
💡 Brute Force (Not Ideal)
- Compare every node from
headA
with every node fromheadB
. - Time: O(m × n)
- ❌ Inefficient
💡 Optimal Approach: Two Pointers
✨ Key Idea
- Use two pointers
pA
andpB
. - Traverse both lists:
- If
pA
reaches end, redirect it toheadB
. - If
pB
reaches end, redirect it toheadA
.
- If
- They will either meet at the intersection node or both become
null
(no intersection).
Why it works:
- Both pointers traverse exactly
m + n
steps.
🔢 Java Code
1 | public class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(m + n)
- Space Complexity: O(1)
✍️ Summary
- This is a textbook two-pointer technique for linked lists.
- Avoids using extra space like hash sets.
- Useful for related problems such as:
lc-142: Linked List Cycle II
lc-21: Merge Two Sorted Lists
Pointer redirection is a simple yet powerful technique when dealing with linked lists of unequal lengths.