Finding Intersection of Two Linked Lists

Day - 50 Intersection of Two Linked Lists The problem - Given the heads of two singly linked lists, return the node at which the two lists intersect. If they don't intersect, return null. Example : listA = [4,1,8,4,5], listB = [5,6,1,8,4,5] → true, intersect at node 8 Brute force - Use HashSet to store nodes from one list, check second list, but the space complexity will be O(n). Approach Used - •) Initialize two pointers: listA = headA, listB = headB. •) While (listA != listB), 1 - If listA != null, move to next, listA = listA.next, else switch to headB. 2 - If listB != null, move to next: listB = listB.next, else switch to headA. •) Return listA. Complexity - Time - O(m + n), both pointers traverse at most m+n nodes. Space - O(1), only used pointers. Note - By switching heads, each pointer travels exactly the same total distance (Length A + Length B). This syncs them up so they hit the intersection at the exact same time! #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories