FastPrepDetermine Whether Two Horses Are Genetically Related

Determine Whether Two Horses Are Genetically Related

Google logoGoogle● MediumNEW GRADINTERNONSITE INTERVIEW

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) → boolean

Examples

Example 1

horseIds = ["Nova","Comet","Blaze"]motherIds = ["","Nova",""]fatherIds = ["","",""]horseA = "Nova"horseB = "Comet"return = true

Comet 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 = true

The 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 = false

A - 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 = true

The two query identifiers name the same horse, which is related to itself by definition.

Constraints

  • 1 <= horseIds.length <= 100,000.
  • motherIds.length == horseIds.length and fatherIds.length == horseIds.length.
  • Every value in horseIds is a unique, non-empty identifier with length from 1 to 50.
  • Every value in motherIds and fatherIds is either the empty string or an identifier with length from 1 to 50.
  • horseA and horseB both appear in horseIds.

More Google problems

See Google hiring insights
Saved
public boolean areHorsesRelated(String[] horseIds, String[] motherIds, String[] fatherIds, String horseA, String horseB) {
    // write your code here

}
horseIds["Nova","Comet","Blaze"]
motherIds["","Nova",""]
fatherIds["","",""]
horseA"Nova"
horseB"Comet"
expectedtrue
Checking account…