Count Ways to Build Rooms in an Ant Colony

Hard

Description

Given a tree representing ant colony rooms, count valid orderings to build all rooms respecting parent-child order. Return count modulo 10^9+7.

Examples

Input:prevRoom = [-1,0,1]
Output:1
Explanation:

Only one valid order.

Input:prevRoom = [-1,0,0,1,2]
Output:6
Explanation:

Works with negative numbers.

Input:prevRoom = [-1,0,0,1,1]
Output:8
Explanation:

Room 0 must be built first. Respecting all dependencies, there are 8 valid build orderings.

Constraints

  • 1 ≤ n ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!