Simple JavaScript solution


  • 0
    W
    var getIntersectionNode = function(headA, headB) {
        var set = {};
        while (headA) {
            set[headA.val] = true;
            headA = headA.next;
        }
        while (headB) {
            if (set[headB.val]) {
                return headB;
            }
            headB = headB.next;
        }
        return null;
    };
    

    Though it's not O(1) space


  • 0
    N
    var getIntersectionNode = function(headA, headB) {
       let hash = {};
       while (headA || headB) {
           
           if (headA) {
               if (hash[headA.val]) {
               return headA;
           }
               hash[headA.val] = true;
               headA = headA.next
           }
           if (headB) {
                if (hash[headB.val]) {
               return headB;
           }
               hash[headB.val] = true;
               headB = headB.next
           } 
       }
       return null;
    };
    

    There is no point in doublw while loop


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.