Square | Frontend Engineer | Remote | August 2021 | Reject
Anonymous User
1881

Who are the { parents, children, grandchildren, grandparents, siblings,... } of { name }?

Let's start with just a small set:
Amy and Bob have children Carol, Doug, Erin
Carol and Xavier have children Mike, Nina

       Amy + Bob  <- we only care about genetic relations, don't fuss about the "+"
       /   |  \
   Doug  Erin  Carol + Xavier
                    / \
                 Mike Nina

build_family([ { parents: [Amy, Bob], children: [Carol, Doug, Erin ] },
{ parents: [Carol, Xavier], children: [Mike, Nina] },
])

input = [
{ 'parents' : ["Amy", "Bob"], 'children' : ["Carol", "Doug", "Erin"] },
{ 'parents' : ["Amy", "Steve"], 'children' : ["Lisa"] },
{ 'parents' : ["Janet", "Bob"], 'children' : ["Harry"] },
{ 'parents' : ["Carol", "Xavier"], 'children' : ["Mike", "Nina"] },
]

I solved this question using traversal on hash map. To find the answer for each relation, I created a seperate function. Wanted to know is there a better way to solve this problem using tries or any other data structure / algorithm. To efficently fetch different relations?

Comments (1)