Intersection Point in Y Shaped Linked Lists | GFG POTD | 13-11-24 | Medium | GFG Problem of the day

Поделиться
HTML-код
  • Опубликовано: 23 ноя 2024

Комментарии • 2

  • @codewithuday
    @codewithuday  11 дней назад

    class Solution {
    public:
    // Function to find intersection point in Y shaped Linked Lists.
    // length function
    int getLen(Node* head){
    int len = 0 ;
    while(head){ len++; head= head->next;}
    return len;
    }
    // head1 -> longest , head2 =smallest;
    int getIntersectionPoint(int diff,Node* head1,Node* head2){
    for(int i = 0 ;inext;
    }
    while(head1 && head2){
    if(head1 == head2) return head1->data;
    head1= head1->next;
    head2= head2->next;
    }
    return -1;
    }
    int intersectPoint(Node* head1, Node* head2) {
    // O(m+n) | O(1)
    int n1 = getLen(head1) ;
    int n2 = getLen(head2);
    int diff =0;
    if(n1 > n2){
    diff = n1 - n2;
    return getIntersectionPoint(diff,head1,head2);
    }
    diff = n2 - n1;
    return getIntersectionPoint(diff,head2,head1);
    }
    };

  • @codewithuday
    @codewithuday  11 дней назад

    class Solution {
    public:
    // Function to find intersection point in Y shaped Linked Lists.
    int intersectPoint(Node* head1, Node* head2) {
    // Your Code Here
    // 2nd Approach
    // O(m+n) | O(m+n)
    unordered_map map;
    while(head1){
    map[head1] = 1;
    head1 = head1->next;
    }
    while(head2){
    if(map[head2]) return head2->data;
    head2 = head2->next;
    }
    return -1;
    }
    };