Intersection of Linked Lists

Using set to track visited nodes

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
ListNode* Solution::getIntersectionNode(ListNode* A, ListNode* B) {
    set<ListNode*> s;
    ListNode *ptr = A;
    while(ptr) {
        s.insert(ptr);
        ptr = ptr -> next;
    }
    
    ptr = B;
    while(ptr) {
        if(s.count(ptr))
            return ptr;
        s.insert(ptr);
        ptr = ptr -> next;
    }
    
    return NULL;
}

Time Complexity: O(n)O(n)​

Space Complexity: O(n)O(n)​

Ignoring Nodes from Longer Linked List

Time Complexity: O(n)O(n)​

Space Complexity: O(1)O(1)​

Last updated