Count Ways to Build Rooms in an Ant Colony - Problem
Count Ways to Build Rooms in an Ant Colony
You are an industrious ant architect tasked with expanding your colony by adding
Room
Your mission: Calculate how many different orders you can build all the rooms in. Since the number can be astronomically large, return the answer modulo
You are an industrious ant architect tasked with expanding your colony by adding
n new rooms numbered 0 to n-1. The construction must follow a specific expansion plan represented as an array prevRoom, where prevRoom[i] indicates that room prevRoom[i] must be built before room i, and these rooms must be directly connected.Room
0 is already built (so prevRoom[0] = -1), and the plan ensures all rooms will eventually be reachable from room 0. The challenge: You can only build one room at a time, and you can only build a room if its prerequisite room already exists.Your mission: Calculate how many different orders you can build all the rooms in. Since the number can be astronomically large, return the answer modulo
109 + 7. Input & Output
example_1.py โ Basic Tree
$
Input:
prevRoom = [-1, 0, 1]
โบ
Output:
1
๐ก Note:
Tree: 0 โ 1 โ 2. Only one valid order: build room 1 first, then room 2. Total ways = 1.
example_2.py โ Tree with Multiple Children
$
Input:
prevRoom = [-1, 0, 0, 1, 2]
โบ
Output:
6
๐ก Note:
Tree: 0 has children [1,2]; 1 has child [3]; 2 has child [4]. Valid orders include [1,3,2,4], [1,2,3,4], [1,2,4,3], [2,4,1,3], [2,1,3,4], [2,1,4,3]. Total ways = 6.
example_3.py โ Single Chain
$
Input:
prevRoom = [-1, 0, 1, 2]
โบ
Output:
1
๐ก Note:
Linear chain: 0 โ 1 โ 2 โ 3. Only one valid order possible: [1,2,3]. Total ways = 1.
Visualization
Tap to expand
Understanding the Visualization
1
Parse Tree Structure
Convert the prevRoom array into a tree where each node knows its children
2
Calculate Subtree Sizes
Use DFS to find how many nodes are in each subtree
3
Apply Combinatorics
For each node with multiple children, calculate how many ways to interleave their construction orders
4
Combine Results
Multiply the arrangements from each subtree to get the final answer
Key Takeaway
๐ฏ Key Insight: By modeling the problem as a tree and using multinomial coefficients, we can count valid orderings in O(n) time without generating them explicitly.
Time & Space Complexity
Time Complexity
O(n! ร n)
Generate n! permutations, each taking O(n) time to validate
โ Quadratic Growth
Space Complexity
O(n)
Space for recursion stack and current permutation
โก Linearithmic Space
Constraints
- n == prevRoom.length
- 2 โค n โค 105
- prevRoom[0] == -1
- 0 โค prevRoom[i] โค n - 1 for i โ 0
- prevRoom represents a valid tree
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code