Python Program For Finding Intersection Point Of Two Linked Lists
Last Updated :
17 Aug, 2023
There are two singly linked lists in a system. By some programming error, the end node of one of the linked list got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge.
Above diagram shows an example with two linked lists having 15 as intersection points.
Method 1(Simply use two loops):
Use 2 nested for loops. The outer loop will be for each node of the 1st list and the inner loop will be for the 2nd list. In the inner loop, check if any of the nodes of the 2nd list is the same as the current node of the first linked list. The time complexity of this method will be O(M * N) where m and n are the numbers of nodes in two lists.
Method 2 (Mark Visited Nodes):
This solution requires modifications to basic linked list data structure. Have a visited flag with each node. Traverse the first linked list and keep marking visited nodes. Now traverse the second linked list, If you see a visited node again then there is an intersection point, return the intersecting node. This solution works in O(m+n) but requires additional information with each node. A variation of this solution that doesn’t require modification to the basic data structure can be implemented using a hash. Traverse the first linked list and store the addresses of visited nodes in a hash. Now traverse the second linked list and if you see an address that already exists in the hash then return the intersecting node.
Method 3(Using difference of node counts):
- Get count of the nodes in the first list, let count be c1.
- Get count of the nodes in the second list, let count be c2.
- Get the difference of counts d = abs(c1 - c2)
- Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes
- Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes)
Below image is a dry run of the above approach:
Below is the implementation of the above approach :
Python3
# Python program to implement
# the above approach
# Defining a node for LinkedList
class Node:
def __init__(self, data):
self.data = data
self.next = None
def getIntersectionNode(head1, head2):
# Finding the total number of elements
# in head1 LinkedList
c1=getCount(head1)
# Finding the total number of elements
# in head2 LinkedList
c2=getCount(head2)
# Traverse the bigger node by 'd' so that
# from that node onwards, both LinkedList
# would be having same number of nodes and
# we can traverse them together.
if c1 > c2:
d = c1 - c2
return _getIntersectionNode(d, head1,
head2)
else:
d = c2 - c1
return _getIntersectionNode(d, head2,
head1)
def _getIntersectionNode(d, head1, head2):
current1 = head1
current2 = head2
for i in range(d):
if current1 is None:
return -1
current1 = current1.next
while current1 is not None and current2 is not None:
# Instead of values, we need to check
# if there addresses are same because
# there can be a case where value is
# same but that value is not an
# intersecting point.
if current1 is current2:
# or current2.data (the value
# would be same)
return current1.data
current1 = current1.next
current2 = current2.next
# Incase, we are not able to find
# our intersecting point.
return -1
# Function to get the count of a LinkedList
def getCount(node):
cur=node
count=0
while cur is not None:
count+=1
cur=cur.next
return count
# Driver code
if __name__ == '__main__':
# Creating two LinkedList
# 1st one: 3->6->9->15->30
# 2nd one: 10->15->30
# We can see that 15 would be
# our intersection point
# Defining the common node
common = Node(15)
#Defining the first LinkedList
head1 = Node(3)
head1.next = Node(6)
head1.next.next = Node(9)
head1.next.next.next = common
head1.next.next.next.next = Node(30)
# Defining the second LinkedList
head2 = Node(10)
head2.next = common
head2.next.next = Node(30)
print("The node of intersection is ",
getIntersectionNode(head1,head2))
# This code is contributed by Ansh Gupta.
Output:
The node of intersection is 15
Time Complexity: O(m+n)
Auxiliary Space: O(1)
Method 4(Make circle in first list):
Thanks to Saravanan Man for providing below solution.
1. Traverse the first linked list(count the elements) and make a circular linked list. (Remember the last node so that we can break the circle later on).
2. Now view the problem as finding the loop in the second linked list. So the problem is solved.
3. Since we already know the length of the loop(size of the first linked list) we can traverse those many numbers of nodes in the second list, and then start another pointer from the beginning of the second list. we have to traverse until they are equal, and that is the required intersection point.
4. remove the circle from the linked list.
Time Complexity: O(m+n)
Auxiliary Space: O(1)
Method 5 (Reverse the first list and make equations):
Thanks to Saravanan Mani for providing this method.
1) Let X be the length of the first linked list until intersection point.
Let Y be the length of the second linked list until the intersection point.
Let Z be the length of the linked list from the intersection point to End of
the linked list including the intersection node.
We Have
X + Z = C1;
Y + Z = C2;
2) Reverse first linked list.
3) Traverse Second linked list. Let C3 be the length of second list - 1.
Now we have
X + Y = C3
We have 3 linear equations. By solving them, we get
X = (C1 + C3 – C2)/2;
Y = (C2 + C3 – C1)/2;
Z = (C1 + C2 – C3)/2;
WE GOT THE INTERSECTION POINT.
4) Reverse first linked list.
Advantage: No Comparison of pointers.
Disadvantage: Modifying linked list(Reversing list).
Time complexity: O(m+n)
Auxiliary Space: O(1)
Method 6 (Traverse both lists and compare addresses of last nodes): This method is only to detect if there is an intersection point or not. (Thanks to NeoTheSaviour for suggesting this)
1) Traverse list 1, store the last node address
2) Traverse list 2, store the last node address.
3) If nodes stored in 1 and 2 are same then they are intersecting.
The time complexity of this method is O(m+n) and used Auxiliary space is O(1)
Please refer complete article on
Write a function to get the intersection point of two Linked Lists for more details!
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read