Determine Whether Two Horses Are Genetically Related
Problem statement
The International Horse Racing Committee maintains birth-certificate data for a collection of horses. Each record identifies a horse and, when known, its mother and father.
Each position i describes one horse:
horseIds[i]is the horse's identifier.motherIds[i]is its mother's identifier, or the empty string""when the mother is unknown.fatherIds[i]is its father's identifier, or the empty string""when the father is unknown.
Relationship rule
For this exercise, assume every non-empty parent entry creates an undirected relationship edge between the horse and that parent. Two horses are genetically related when a path of one or more such parent-child edges connects them. A horse is also related to itself.
A non-empty parent identifier may refer to a horse that does not have its own record in horseIds.
Required result
Return true when horseA and horseB belong to the same connected component of this relationship graph. Otherwise, return false.
Function
areHorsesRelated(horseIds: String[], motherIds: String[], fatherIds: String[], horseA: String, horseB: String) → booleanExamples
Example 1
horseIds = ["Nova","Comet","Blaze"]motherIds = ["","Nova",""]fatherIds = ["","",""]horseA = "Nova"horseB = "Comet"return = trueComet lists Nova as its mother, so one parent-child edge directly connects the queried horses.
Example 2
horseIds = ["Atlas","Bella","Colt"]motherIds = ["","","Atlas"]fatherIds = ["","","Bella"]horseA = "Atlas"horseB = "Bella"return = trueThe path Atlas - Colt - Bella connects the two queried horses through their shared child record.
Example 3
horseIds = ["A","B","C","D"]motherIds = ["","A","","C"]fatherIds = ["","","",""]horseA = "B"horseB = "D"return = falseA - B and C - D are separate connected components, so no relationship path joins B to D.
Example 4
horseIds = ["Solo"]motherIds = [""]fatherIds = [""]horseA = "Solo"horseB = "Solo"return = trueThe two query identifiers name the same horse, which is related to itself by definition.
Constraints
1 <= horseIds.length <= 100,000.motherIds.length == horseIds.lengthandfatherIds.length == horseIds.length.- Every value in
horseIdsis a unique, non-empty identifier with length from1to50. - Every value in
motherIdsandfatherIdsis either the empty string or an identifier with length from1to50. horseAandhorseBboth appear inhorseIds.