Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Intersection of Two Linked Lists

Brute force

Hashing improvement

Constant space O(N) Time optimization

Code

class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB)
    {
        if (headA == NULL || headB == NULL) return NULL; // Remember this case also, you forgot

        int len1 = 0, len2 = 0;
        ListNode *ptr1 = headA, *ptr2 = headB;
        while (ptr1 != NULL) {
            len1++;
            ptr1 = ptr1->next;
        }
        while (ptr2 != NULL) {
            len2++;
            ptr2 = ptr2->next;
        }
        ptr1 = headA, ptr2 = headB;
        if (len1 > len2) {
            int temp = len1 - len2;
            while (temp--) {
                ptr1 = ptr1->next;
            }
        } else {
            int temp = len2 - len1;
            while (temp--) {
                ptr2 = ptr2->next;
            }
        }

        while (ptr1 != NULL && ptr2 != NULL) {
            if (ptr1 == ptr2) {
                return ptr1;
            }
            ptr1 = ptr1->next;
            ptr2 = ptr2->next;
        }
        return NULL;
    }
};

Same complexity another method.

class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB)
    {
        if (headA == NULL || headB == NULL) return NULL;

        ListNode *ptr1 = headA, *ptr2 = headB;

        while (ptr1 != ptr2) {
            ptr1 = (ptr1 == NULL) ? headB : ptr1->next;
            ptr2 = (ptr2 == NULL) ? headA : ptr2->next;
        }
        return ptr1;
    }
};

Codestudio

#include <bits/stdc++.h>
int findIntersection(Node *fh, Node *sh)
{
    if(!fh || !sh) return -1;
    Node* p1 = fh, *p2= sh;
    while(p1!=p2){
        if(p1==NULL){
            p1 = sh;
        }else{
            p1 = p1->next;
        }
        if(p2==NULL){
            p2 = fh;
        }else {
            p2 = p2->next;
        }
    }
    if(p1==NULL) return -1;
    return p1->data;
}