Count Ways to Build Rooms in an Ant Colony Problem
Description
LeetCode Problem 1916.
You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0.
You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected. You can choose to build any room as long as its previous room is already built.
Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 10^9 + 7.
Example 1:
Input: prevRoom = [-1,0,1]
Output: 1
Explanation: There is only one way to build the additional rooms: 0 → 1 → 2
Example 2:
Input: prevRoom = [-1,0,0,1,2]
Output: 6
Explanation:
The 6 ways are:
0 → 1 → 3 → 2 → 4
0 → 2 → 4 → 1 → 3
0 → 1 → 2 → 3 → 4
0 → 1 → 2 → 4 → 3
0 → 2 → 1 → 3 → 4
0 → 2 → 1 → 4 → 3
Constraints:
n == prevRoom.length2 <= n <= 10^5prevRoom[0] == -10 <= prevRoom[i] < nfor all1 <= i < n- Every room is reachable from room
0once all the rooms are built.
Solution
Approach: Counting Topological Orders of a Tree
The plan is a tree rooted at room 0: a room can be built once its parent exists. An order that respects this is a topological order of the tree.
The number of such orders has a closed form. Of the n! permutations of all rooms, each room v must come before everything in its subtree, which happens in a 1 / size(v) fraction of them, independently over the whole tree. So
answer = n! / (size(1) * size(2) * ... * size(n)) (mod 109 + 7),
where size(v) is the number of rooms in the subtree of v (including v).
To compute it, build the child lists, list the rooms in BFS order from room 0, and add each room's size to its parent while walking that order backwards (no recursion, so a chain of 105 rooms is safe). Division is done with modular inverses; the inverses of 1..n come from the linear recurrence inv[i] = -(p / i) * inv[p mod i] mod p.
Complexity: O(n) time and O(n) space.
class Solution:
def waysToBuildRooms(self, prevRoom: List[int]) -> int:
mod = 10**9 + 7
n = len(prevRoom)
children = [[] for _ in range(n)]
for i in range(1, n):
children[prevRoom[i]].append(i)
order = [0] # BFS order from the root
for u in order:
order.extend(children[u])
size = [1] * n
for u in reversed(order):
if u:
size[prevRoom[u]] += size[u]
inv = [0, 1] + [0] * (n - 1) # inverses of 1..n modulo mod
for i in range(2, n + 1):
inv[i] = (mod - mod // i) * inv[mod % i] % mod
ans = 1
for i in range(1, n + 1):
ans = ans * i % mod
for s in size:
ans = ans * inv[s] % mod
return ans