AlgoMaster Logo

Intersection of Two Linked Lists

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest method to determine if the linked lists intersect is to compare each node in one list with every node in the other list. If there is a node that matches, then that node is the intersection node.

Code:

2. HashSet

Intuition:

We can use a hash set to store all the nodes of one of the linked lists, then traverse the second linked list to see if any node is already in the set. If a node is found in the set, that node is the intersection node.

Code:

3. Two Pointers

Intuition:

The most optimal approach uses two pointers. Initially, set two pointers to the heads of the two linked lists. Traverse through the linked lists, and when a pointer reaches the end of a linked list, redirect it to the head of the other linked list. If the lists intersect, the two pointers will eventually converge at the intersection node after (m + n) - c steps, where c is the length of the shared tail. If they don't intersect, both pointers will eventually become null, and the loop will end.

Code: