Leetcode #1916: Count Ways to Build Rooms in an Ant Colony
In this guide, we solve Leetcode #1916 Count Ways to Build Rooms in an Ant Colony in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Tree, Graph, Topological Sort, Math, Dynamic Programming, Combinatorics
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: prevRoom = [-1,0,1]
Output: 1
Explanation: There is only one way to build the additional rooms: 0 → 1 → 2
Python Solution
class Solution:
def waysToBuildRooms(self, prevRoom: List[int]) -> int:
modulo = 10**9 + 7
ingoing = defaultdict(set)
outgoing = defaultdict(set)
for i in range(1, len(prevRoom)):
ingoing[i].add(prevRoom[i])
outgoing[prevRoom[i]].add(i)
ans = [1]
def recurse(i):
if len(outgoing[i]) == 0:
return 1
nodes_in_tree = 0
for v in outgoing[i]:
cn = recurse(v)
if nodes_in_tree != 0:
ans[0] *= comb(nodes_in_tree + cn, cn)
ans[0] %= modulo
nodes_in_tree += cn
return nodes_in_tree + 1
recurse(0)
return ans[0] % modulo
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.