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
Problem: Count Ways to Build Rooms in Ant ColonyInput: prevRoom = [-1, 0, 0, 1, 2]Dependency Array01234Tree Structure:• Room 0 (root)• Rooms 1,2 depend on 0• Room 3 depends on 1• Room 4 depends on 2Output: 8 different valid building orders
Understanding the Visualization
1
Input Dependencies
prevRoom array defines parent-child relationships
2
Tree Structure
Convert to tree where each room depends on its parent
3
Count Arrangements
Calculate valid building orders respecting dependencies
Key Takeaway
🎯 Key Insight: Dependencies form a tree structure, and arrangements can be calculated using multinomial coefficients
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