• + 0 comments

    My Java solution with o(n) time and o(1) space:

    static int findMergeNode(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
            //use two ptrs to track head1 and head2
            SinglyLinkedListNode first = head1;
            SinglyLinkedListNode second = head2;
            
            while(first != second){
                first = (first.next != null) ? first.next : head2;
                second = (second.next != null) ? second.next : head1;
            }
            
            return first != null ? first.data : -1; //no merge node found
        }