Problem · Tree
Find Defenders Against Every Hostile Monster
Learn this problemProblem statement
A nested monster hierarchy has been flattened into three parallel arrays. names[i] is monster i's unique name, hostile[i] says whether it is hostile, and parent[i] is the index of the monster that can directly defeat it. A root has parent -1.
Defeat is transitive: if monster A can defeat B and B can defeat C, then A can defeat C.
Return the names of every non-hostile monster that can defeat every hostile monster. Preserve input order in the result.
Function
findDefenders(names: String[], parent: int[], hostile: boolean[]) → String[]Examples
Example 1
names = ["dragon","griffin","orc","imp"]parent = [-1,0,0,2]hostile = [false,false,true,true]return = ["dragon"]Dragon can defeat both hostile monsters through its descendants. Griffin cannot, and hostile monsters are not eligible defenders.
Example 2
names = ["atlas","guardian","rat"]parent = [-1,0,1]hostile = [false,false,true]return = ["atlas","guardian"]Both Atlas and Guardian have Rat in their transitive can-defeat subtree.
Example 3
names = ["oak","wolf","elm","goblin"]parent = [-1,0,-1,2]hostile = [false,true,false,true]return = []The hostile monsters lie in different trees, so no monster can defeat both.
Constraints
1 <= names.length <= 200000.parent.length == hostile.length == names.length.- Names are unique non-empty lowercase strings.
- Each
parent[i]is-1or a valid different index. - The parent relations form a forest with no cycles.
- At least one monster is hostile.