DEV Community

Cover image for Day 89 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 89 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/intersection-point-in-y-shapped-linked-lists/1

Intersection in Y Shaped Lists

Difficulty: Medium Accuracy: 44.67%

You are given the heads of two non-empty singly linked lists, head1 and head2, that intersect at a certain point. Return that Node where these two linked lists intersect.
Note: It is guaranteed that the intersected node always exists.
In the custom input you have to give input for CommonList which pointed at the end of both head1 and head2 to form a Y-shaped linked list.
Examples:
Input: head1: 10 -> 15 -> 30, head2: 3 -> 6 -> 9 -> 15 -> 30

Output: 15
Explanation: From the above image, it is clearly seen that the common part is 15 -> 30, whose starting point is 15.

Input: head1: 4 -> 1 -> 8 -> 5, head2: 5 -> 6 -> 1 -> 8 -> 5

Output: 1
Explanation: From the above image, it is clearly seen that the common part is 1 -> 8 -> 5, whose starting point is 1.

Constraints:
2 ≀ total number of nodes ≀ 2*105
-104 ≀ node->data ≀ 104

Solution:
class Solution:
def intersectPoint(self, head1, head2):

    def length(head):
        curr = head
        ans = 0
        while curr:
            ans += 1
            curr = curr.next
        return ans

    l1,l2 = length(head1),length(head2)

    if l1>l2:
        for _ in range(l1-l2):
            head1 = head1.next
    else:
        for _ in range(l2-l1):
            head2 = head2.next

    while(head1 != head2):
        head1 = head1.next
        head2 = head2.next

    return head1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)