FastPrepDetermine Whether Two Chickens Are Blood Relatives

Determine Whether Two Chickens Are Blood Relatives

Google logoGoogle● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

A chicken family is represented by direct parent lists. parents[i] contains every direct parent of chicken i. Parent edges form a directed acyclic graph.

Two chickens are blood relatives when their ancestor sets intersect. A chicken is included in its own ancestor set, so an ancestor and descendant are relatives. Merely sharing a child does not make two co-parents blood relatives.

Return whether first and second are blood relatives.

Function

areBloodRelatives(parents: int[][], first: int, second: int) → boolean

Examples

Example 1

parents = [[],[],[0,1],[0,1]]first = 2second = 3return = true

The two chickens share parents 0 and 1.

Example 2

parents = [[],[],[0,1]]first = 0second = 1return = false

The two co-parents share a child but no ancestor.

Example 3

parents = [[],[0],[1]]first = 0second = 2return = true

Chicken 0 is an ancestor of chicken 2.

Constraints

  • 1 <= parents.length <= 200000.
  • Every listed parent is a valid node index.
  • The total number of parent edges is at most 300000.
  • The parent graph is acyclic.
  • first and second are valid indices.

More Google problems

See Google hiring insights
public boolean areBloodRelatives(int[][] parents, int first, int second) {
    // Write your code here.
}
parents[[],[],[0,1],[0,1]]
first2
second3
expectedtrue
Checking account…