<p>You are an ant tasked with adding <code>n</code> new rooms numbered <code>0</code> to <code>n-1</code> to your colony. You are given the expansion plan as a <strong>0-indexed</strong> integer array of length <code>n</code>, <code>prevRoom</code>, where <code>prevRoom[i]</code> indicates that you must build room <code>prevRoom[i]</code> before building room <code>i</code>, and these two rooms must be connected <strong>directly</strong>. Room <code>0</code> is already built, so <code>prevRoom[0] = -1</code>. The expansion&nbsp;plan is given such that once all the rooms are built, every room will be reachable from room <code>0</code>.</p>

<p>You can only build <strong>one room</strong> at a time, and you can travel freely between rooms you have <strong>already built</strong> only if they are <strong>connected</strong>.&nbsp;You can choose to build <strong>any room</strong> as long as its <strong>previous room</strong>&nbsp;is already built.</p>

<p>Return <em>the <strong>number of different orders</strong> you can build all the rooms in</em>. Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/19/d1.JPG" style="width: 200px; height: 212px;" />
<pre>
<strong>Input:</strong> prevRoom = [-1,0,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong>&nbsp;There is only one way to build the additional rooms: 0 &rarr; 1 &rarr; 2
</pre>

<p><strong class="example">Example 2:</strong></p>
<strong><img alt="" src="https://assets.leetcode.com/uploads/2021/06/19/d2.JPG" style="width: 200px; height: 239px;" /></strong>

<pre>
<strong>Input:</strong> prevRoom = [-1,0,0,1,2]
<strong>Output:</strong> 6
<strong>Explanation:
</strong>The 6 ways are:
0 &rarr; 1 &rarr; 3 &rarr; 2 &rarr; 4
0 &rarr; 2 &rarr; 4 &rarr; 1 &rarr; 3
0 &rarr; 1 &rarr; 2 &rarr; 3 &rarr; 4
0 &rarr; 1 &rarr; 2 &rarr; 4 &rarr; 3
0 &rarr; 2 &rarr; 1 &rarr; 3 &rarr; 4
0 &rarr; 2 &rarr; 1 &rarr; 4 &rarr; 3
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == prevRoom.length</code></li>
	<li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li>
	<li><code>prevRoom[0] == -1</code></li>
	<li><code>0 &lt;= prevRoom[i] &lt; n</code> for all <code>1 &lt;= i &lt; n</code></li>
	<li>Every room is reachable from room <code>0</code> once all the rooms are built.</li>
</ul>
MOD = 1000000007

class Solution:
    def __init__(self):
        self.fact = []
        self.ifact = []

    # Utility function to perform modular exponentiation
    def mod_exp(self, base: int, exp: int, mod: int) -> int:
        result = 1
        while exp > 0:
            if exp % 2 == 1:
                result = (result * base) % mod
            base = (base * base) % mod
            exp //= 2
        return result

    # Function to calculate factorial and factorial inverse arrays
    def prepare_factorials(self, n: int, mod: int) -> None:
        self.fact = [1] * (n + 1)
        self.ifact = [1] * (n + 1)
        for i in range(1, n + 1):
            self.fact[i] = (self.fact[i - 1] * i) % mod
        self.ifact[n] = self.mod_exp(self.fact[n], mod - 2, mod)  # Fermat's little theorem for modular inverse
        for i in range(n - 1, -1, -1):
            self.ifact[i] = (self.ifact[i + 1] * (i + 1)) % mod

    # Recursive DP function to count ways and calculate subtree sizes
    def count_ways(self, u: int, ways: List[int], size: List[int], graph: List[List[int]], fact: List[int], ifact: List[int], mod: int) -> None:
        ways[u] = 1  # Initialize ways for the current node
        size[u] = 1  # Initialize size for the current node
        product = 1  # Initialize product for the current node
        total_size = 0  # Initialize total size for the current subtree

        for v in graph[u]:
            self.count_ways(v, ways, size, graph, fact, ifact, mod)  # Recursively count ways for the child node
            product = (product * ways[v]) % mod  # Multiply ways of the child node
            product = (product * ifact[size[v]]) % mod  # Multiply inverse factorial of the size of the child subtree
            total_size += size[v]  # Update total size of the current subtree
        
        size[u] += total_size  # Update the size of the current node
        ways[u] = (fact[total_size] * product) % mod  # Calculate the number of ways for the current node

    def waysToBuildRooms(self, prevRoom: List[int]) -> int:
        n = len(prevRoom)  # Number of rooms

        # Prepare factorial and inverse factorial arrays
        self.prepare_factorials(n, MOD)

        # Create adjacency list for the graph
        graph = [[] for _ in range(n)]

        # Populate the adjacency list
        for i in range(1, n):
            parent = prevRoom[i]
            graph[parent].append(i)

        # Allocate memory for ways and size arrays
        ways = [0] * n
        size = [0] * n

        # Start DP from the root (room 0)
        self.count_ways(0, ways, size, graph, self.fact, self.ifact, MOD)

        return ways[0]  # The result is the number of ways to build from the root
1194