There are N persons in a country. N is very big in millions. Design a efficient data structure and algorithm to find out whether there is blood relations between given two person or say they have a common ancestor . My solution: Used a map //UID by Nandan Nilekani :) struct person { struct person *father; struct person *mother; list child; //However may not be needed for this problem string name ...i.e. //Add more } struct person * findAncestor ( struct person *a, struct person *b) { Take first node in stack. While ( stack is not null ) { Mark Node. Push Its ancestor in stack; } Take second node in stack. while ( stack is not null ) { If marked return Node, push ancestor in stack. } return NULL; } It has a drawback, i need to clear the flagged node before i apply the search algorithm again. But till now the best i know.
Collection of Interview Question on Data structure, Algorithm, Java, C++ and more