Saturday, 18 April 2015

Hackerrank Find Merge Point of Two Lists solution

Problem Statement

This challenge is part of a tutorial track by MyCodeSchool

You’re given the pointer to the head nodes of two linked lists that merge together at some node. Find the node at which this merger happens. The two head nodes will be different and neither will be NULL.

Source code:

   Find merge point of two linked lists  
   Node is defined as  
   struct Node  
     int data;  
     Node* next;  
 int FindMergeNode(Node *headA, Node *headB)  
   // Complete this function  
   // Do not write the main method.   
   Node *tempB;  
     tempB = headB;  
       if(tempB == headA){  
         return tempB->data;  
       tempB = tempB->next;  
     headA = headA->next;  
   return headA->data;  

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

1 comment:

  1. Save the pointers of first list into a hashmap. Then traverse the the second list and compare the pointers with those in map. It's better than the above solution.
    -- Suhas