DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

Intersection of Two Linked Lists — My First Working Approach

When I first solved LeetCode 160: Intersection of Two Linked Lists, I focused on understanding what “intersection” actually means.

This article explains:

  1. how I approached the problem
  2. why my solution works
  3. what other (more optimal) approaches exist

Problem Understanding

You are given the heads of two singly linked lists.

Your task:

Return the node where the two linked lists intersect.
If they do not intersect, return null.

Important clarification

Intersection means same node in memory not same value.So comparison must be:

nodeA == nodeB
Enter fullscreen mode Exit fullscreen mode

not

nodeA->val == nodeB->val.
Enter fullscreen mode Exit fullscreen mode

My Approach: Brute Force Pointer Comparison

Idea

Traverse every node in list A for each node in A, traverse all nodes in list B.If both pointers point to the same node → intersection found

C++ Code

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *i;
        ListNode *j;

        for (i = headA; i != NULL; i = i->next) {
            for (j = headB; j != NULL; j = j->next) {
                if (i == j)
                    return i; // intersection found
            }
        }
        return NULL; // no intersection
    }
};
Enter fullscreen mode Exit fullscreen mode

Why This Works

  • Every possible pair of nodes is checked
  • Pointer comparison ensures we detect actual shared nodes
  • The moment two pointers match, we return that node
  • This guarantees correctness.

Complexity Analysis

Time Complexity O(n × m)
Space Complexity O(1)
Enter fullscreen mode Exit fullscreen mode

✔️ Correct solution
❌ Not optimal due to nested loops

Other Approaches Exist (Just Awareness)

After solving this, I learned that there are better approaches:

Two pointer switching technique (most optimal)
Hashing using unordered_set
Length difference alignment method
These reduce time complexity to O(n + m).

But at this stage, my goal was. First solve correctly, then optimize.

What I Learned

  1. Intersection is about memory address, not values
  2. Pointer comparison (==) is critical
  3. Solving with brute force is a valid learning step
  4. Optimization comes after understanding

Final Thoughts

This solution helped me build confidence with:

linked list traversal
pointer comparison
reasoning about memory-level behavior

Even though it’s not optimal, it’s a strong foundational solution — and a necessary step before mastering the optimal patterns.

Top comments (1)

Collapse
 
charles_kumar_30654e10958 profile image
Charles Kumar

step by step improvement is the key here

One Step at a TIme