1
# Runtime: 4732 ms (Top 93.33%) | Memory: 177.5 MB (Top 6.67%)3
def waysToBuildRooms(self, prevRoom: List[int]) -> int:7
mod_inverses = [1] * (n + 1)8
factorials = [1] * (n + 1)9
inverse_factorials = [1] * (n + 1)13
): # Precompute all factorials and inverse factorials needed in O(1) time each14
mod_inverses[x] = mod - mod // x * mod_inverses[mod % x] % mod15
factorials[x] = (x * factorials[x - 1]) % mod16
inverse_factorials[x] = (mod_inverses[x] * inverse_factorials[x - 1]) % mod18
children = collections.defaultdict(20
) # Convert parent list to children lists21
for i, x in enumerate(prevRoom[1:], 1):24
def postorder(curr: int) -> Tuple[int, int]:25
if curr not in children: # Leaf has ways, size both 129
for child in children[curr]:30
ways, size_of = postorder(child)31
tot_ways *= ways * inverse_factorials[size_of]33
tot_ways *= factorials[tot_size - 1]34
return tot_ways % mod, tot_size36
return postorder(0)[0]