Count Ways to Build Rooms in an Ant Colony - Problem

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

Input & Output

Example 1 — Basic Tree
$ Input: prevRoom = [-1,0,1,2]
Output: 1
💡 Note: Only one valid order: build rooms in sequence 0→1→2→3 since each room depends on the previous one
Example 2 — Multiple Children
$ Input: prevRoom = [-1,0,0,1,2]
Output: 8
💡 Note: Room 0 has children 1,2. Room 1 has children 3,4. Multiple valid orders exist like: 0→1→2→3→4, 0→1→3→2→4, etc.
Example 3 — Single Path
$ Input: prevRoom = [-1,0]
Output: 1
💡 Note: Only two rooms: 0 is already built, then build room 1. Only one possible order.

Constraints

  • 1 ≤ n ≤ 105
  • prevRoom[0] == -1
  • 0 ≤ prevRoom[i] ≤ n - 1 for all 1 ≤ i ≤ n - 1
  • prevRoom represents a valid tree

Visualization

Tap to expand
Count Ways to Build Rooms in an Ant Colony INPUT Tree Structure (prevRoom) 0 1 2 3 prevRoom = [-1, 0, 1, 2] ALGORITHM STEPS 1 Build Tree Convert prevRoom to tree 2 DFS Traversal Post-order: 3, 2, 1, 0 3 Count Subtree Sizes size[i] = 1 + sum(children) 4 Calculate Ways Multinomial coefficients Subtree Sizes: Node 3: size = 1 Node 2: size = 2 Node 1: size = 3 Node 0: size = 4 FINAL RESULT Build Order (Only 1 way): 0 --> 1 --> 2 --> 3 Linear chain = no branching Only one valid sequence! OUTPUT 1 OK - Verified Key Insight: For a linear tree (chain), there's only ONE way to build rooms since each room depends on the previous one. For branching trees: ways = product of (subtree_size - 1)! / product of child_subtree_sizes! using multinomial formula. DFS computes subtree sizes bottom-up, then calculates the number of valid topological orderings. TutorialsPoint - Count Ways to Build Rooms in an Ant Colony | DFS with Tree Structure Approach
Asked in
Google 25 Microsoft 18 Amazon 15 Facebook 12
28.0K Views
Medium Frequency
~35 min Avg. Time
892 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