Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 109 + 7.
Example 1:
Input: prevRoom = [-1,0,1] Output: 1 Explanation: There is only one way to build the additional rooms: 0 → 1 → 2
Example 2:
Input: prevRoom = [-1,0,0,1,2] Output: 6 Explanation: The 6 ways are: 0 → 1 → 3 → 2 → 4 0 → 2 → 4 → 1 → 3 0 → 1 → 2 → 3 → 4 0 → 1 → 2 → 4 → 3 0 → 2 → 1 → 3 → 4 0 → 2 → 1 → 4 → 3
Constraints:
n == prevRoom.length2 <= n <= 105prevRoom[0] == -10 <= prevRoom[i] < n for all 1 <= i < n0 once all the rooms are built.Problem summary: 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 109 + 7.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Dynamic Programming · Tree · Topological Sort
[-1,0,1]
[-1,0,0,1,2]
count-anagrams)count-the-number-of-good-subsequences)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1916: Count Ways to Build Rooms in an Ant Colony
// Auto-generated Java example from py.
class Solution {
public void exampleSolution() {
}
}
// Reference (py):
// # Accepted solution for LeetCode #1916: Count Ways to Build Rooms in an Ant Colony
// 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
// Accepted solution for LeetCode #1916: Count Ways to Build Rooms in an Ant Colony
// Auto-generated Go example from py.
func exampleSolution() {
}
// Reference (py):
// # Accepted solution for LeetCode #1916: Count Ways to Build Rooms in an Ant Colony
// 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
# Accepted solution for LeetCode #1916: Count Ways to Build Rooms in an Ant Colony
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
// Accepted solution for LeetCode #1916: Count Ways to Build Rooms in an Ant Colony
/**
* [1916] Count Ways to Build Rooms in an Ant Colony
*
* 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^9 + 7.
*
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/19/d1.JPG" style="width: 200px; height: 212px;" />
*
* Input: prevRoom = [-1,0,1]
* Output: 1
* Explanation: There is only one way to build the additional rooms: 0 → 1 → 2
*
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/19/d2.JPG" style="width: 200px; height: 239px;" />
*
*
* Input: prevRoom = [-1,0,0,1,2]
* Output: 6
* Explanation:
* The 6 ways are:
* 0 → 1 → 3 → 2 → 4
* 0 → 2 → 4 → 1 → 3
* 0 → 1 → 2 → 3 → 4
* 0 → 1 → 2 → 4 → 3
* 0 → 2 → 1 → 3 → 4
* 0 → 2 → 1 → 4 → 3
*
*
*
* Constraints:
*
*
* n == prevRoom.length
* 2 <= n <= 10^5
* prevRoom[0] == -1
* 0 <= prevRoom[i] < n for all 1 <= i < n
* Every room is reachable from room 0 once all the rooms are built.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/
// discuss: https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn ways_to_build_rooms(prev_room: Vec<i32>) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1916_example_1() {
let prev_room = vec![-1, 0, 1];
let result = 1;
assert_eq!(Solution::ways_to_build_rooms(prev_room), result);
}
#[test]
#[ignore]
fn test_1916_example_2() {
let prev_room = vec![-1, 0, 0, 1, 2];
let result = 6;
assert_eq!(Solution::ways_to_build_rooms(prev_room), result);
}
}
// Accepted solution for LeetCode #1916: Count Ways to Build Rooms in an Ant Colony
// Auto-generated TypeScript example from py.
function exampleSolution(): void {
}
// Reference (py):
// # Accepted solution for LeetCode #1916: Count Ways to Build Rooms in an Ant Colony
// 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
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.