The Problem:
In this problem, we are given 2 linked lists that have common node at some point, we have to return the node at which they intersect. This problem is pretty similar to the Linked List Cycle Problem we did a couple days ago.
Before we begin trying to figure out a solution for this problem, let’s first revisit an important concepts Linked List and Recursion.
Understanding Recursion:
Recursion is essentially a function calling itself. It is frequently used to solve problems that can be divided into smaller, similar sub-problems and can be very useful in dynamic programming. To understand recursion, it can be helpful to break it down into 3 parts:
- Base Condition: This condition prevents the recursive function from calling itself infinitely.
- Recursive Call: This is responsible for calling the recursive function itself.
- Small Calculation: This step, which can come before or after the Recursive Call, is responsible for performing some calculation that we need for the recursive function or for returning some result after a recursive call has been completed.
A recursive tree is a visual representation of the recursive calls made by a function. It can be very helpful in understanding how recursion works and in analyzing the time and space complexity of recursive algorithms.
Understanding Linked List:
A linked list is a linear data structure that consists of a sequence of nodes, each containing data and a reference to the next node in the list. It is often used as an alternative to arrays, as it can be more efficient in certain operations such as insertion and deletion.
To understand linked lists, it can be helpful to break it down into 3 parts:
- Nodes: Each node in a linked list contains some data and a reference to the next node in the list.
- Head: The head of a linked list is the first node in the list. It is used as the starting point for many operations on the list.
- Traversal: Traversing a linked list involves starting at the head and following the references from one node to the next until the desired node is reached or the end of the list is reached.
Linked lists can be very useful in solving problems that involve dynamic data structures, as they allow for efficient insertion and deletion of elements. They can also be used in combination with other data structures, such as stacks and queues, to solve more complex problems.
Intuition & Algorithm:
With an understanding of how recursion and linked lists work, let’s try to break down the problem. We don’t need to create our own linked list data structure because it is already provided. This is a fairly straightforward problem, so we will begin by figuring out the base condition, which in this case would be when the recursion reaches the end of the linked list (head == None).
Borrowing the idea from the similar question, we can then check the cache for the current list node (we don't have to worry about figuring out ways to hash the linked list node as each object has a unique object identifier and it can be used as a key in a hashMap.) If we find the current node in the hashMap then we simply return the node else we add the current node to the hashMap, move forward by updating the current node to the next node and call the function recursively till we hit the base condition or find a cycle. We can use the same hashMap for both the lists and run the recursive function on both the linked lists.
This ensures that we will always be able to find the intersection node (if it exist) between 2 linked lists.
Summary of Solution
Use recursion and a hash map to check if 2 linked lists intersect. Store the current node in the hash map and call the function recursively on the next node. If the current node is already in the hash map, return the node. Otherwise, return None when the recursion reaches the end of the linked list (head == None). Traverse both linked lists using the same hashMap.
Code
This can be translated to code in the following way:
Solution.py
lang: python
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:hashMap = {}def helper(head, hashMap):if head == None: # base casereturn headelif head in hashMap: # calculationreturn headelse:hashMap[head] = 1head = head.nextreturn helper(head, hashMap) # recursive calla = helper(headA, hashMap)return helper(headB, hashMap)
- Time Complexity O(m+n)
- Space Complexity O(min(m,n))
The time complexity of this solution is O(m+n) This is because the function needs to traverse both linked lists to calculate the size.
Space complexity is O(min(m,n)) because the code uses a hash map to store the nodes it has visited, and in the worst case, it will need to store all the nodes in the shorter of the two linked lists.
This approach is simple and efficient, making it a good solution to this problem.