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 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.

Constraints

  • n == prevRoom.length
  • 2 โ‰ค n โ‰ค 105
  • prevRoom[0] == -1
  • 0 โ‰ค prevRoom[i] โ‰ค n - 1 for i โ‰  0
  • prevRoom represents a valid tree

Visualization

Tap to expand
Ant Colony Construction PlanningCEORoom 0Already BuiltMGR ARoom 1MGR BRoom 2MGR CRoom 3EMP 1EMP 2Subtree A (Room 1)Size: 3 nodesArrangements:3!/(2!) = 3 waysRoom 2Size: 1 nodeWays: 1Room 3Size: 1 nodeWays: 1Final CalculationTotal arrangements:5!/(3!ร—1!ร—1!) ร— 3 ร— 1 ร— 1= 20 ร— 3 = 60
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.
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 21
67.2K Views
Medium Frequency
~35 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen