Skip to main content

Count Ways to Build Rooms in an Ant Colony - Solution & Explanation

HardMathDynamic ProgrammingTreeGraph17 min readAsked at: Adobe
Practice this problem

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. 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.length
  • 2 <= n <= 105
  • 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.

Approach Overview

Problem Overview: You are given a tree where each node represents a room and prevRoom[i] indicates which room must be built before room i. Room 0 is already built. The task is to count how many different valid orders exist to build all rooms while respecting these parent dependencies.

Approach 1: DFS and Combinatorics (O(n) time, O(n) space)

Treat the dependency structure as a rooted tree. Each subtree can be built independently once its parent is finished. During a DFS, compute the size of each subtree and the number of valid ways to arrange nodes inside it. When combining children, use combinatorics: if subtrees have sizes s1, s2, ..., the number of ways to interleave them is a multinomial coefficient. Precompute factorials and modular inverses to evaluate combinations under modulo. This approach leverages tree traversal and combinatorics to merge subtree results efficiently.

Approach 2: Dynamic Programming with Tree Representation (O(n) time, O(n) space)

Build an adjacency list from the parent array and run a DFS that returns two values for each node: the number of nodes in its subtree and the number of valid build orders for that subtree. While processing children, accumulate subtree sizes and multiply the child arrangements with combination counts representing interleavings. The DP state essentially captures "ways to build this subtree" while respecting dependencies. This formulation fits naturally with dynamic programming on trees.

Approach 3: Combination Mathematics in Tree (O(n) time, O(n) space)

The mathematical perspective models the problem as counting valid topological orders of a rooted tree. For each node with children subtrees of sizes s1, s2, ..., you place their nodes among s1 + s2 + ... slots. The number of placements equals (s1+s2+...)! / (s1! * s2! * ...). Multiply this with the number of arrangements inside each subtree. Precompute factorials and inverse factorials once, then evaluate each combination in constant time.

Approach 4: Topological Sort with Dynamic Programming (O(n) time, O(n) space)

Interpret the dependency tree as a DAG and process nodes using a topological sort. Maintain DP values representing ways to construct partial subgraphs and combine them when prerequisites are satisfied. Although the structure is still a tree, framing it as a topological ordering problem helps when reasoning about dependency scheduling and incremental state transitions.

Recommended for interviews: DFS with combinatorics is the expected solution. It shows you understand how subtree independence leads to multinomial combinations. A brute-force enumeration of topological orders quickly becomes exponential, while the combinatorial tree DP reduces the problem to linear time with precomputed factorials.

Approach 1: Dynamic Programming with Tree Representation

Represent the problem as a tree with each node referring to a room, and edges between nodes pointing to prerequisite dependencies. Use a dynamic programming approach to count the number of permutations facilitated by the tree structure.

Consider breaking down the problem into subproblems based on subtrees and calculate the number of valid orders for each subtree.

This code represents the rooms in a tree structure using a directed graph with nodes and edges indicating the prerequisite room. We use a depth-first search (DFS) approach to traverse the tree, computing permutations dynamically at each node (room) level using combination mathematics. A 2D list is precomputed for combination calculations using Pascal's Triangle logic.

Code

Python

Complexity

Time Complexity: O(n^2), where n is the number of rooms, due to combinations precomputation. Space Complexity: O(n^2) for the combination table to store computed values.

Try this approach in the editor β†’

Approach 2: Combination Mathematics in Tree

Use tree structure to identify dependent builds. Solve using DFS with combination calculations derived from subtree sizes. This approach merges combinatorial logic into tree traversal to efficiently calculate possible room-building sequences.

This JavaScript function leverages a tree structure and employs a recursive DFS approach to compute room-building permutations. Combinatorial logic is embedded into the recursion to account for subtree permutation combinations. A cache optimizes combination computations based on Pascal’s Triangle principles.

Code

JavaScript

Complexity

Time Complexity: O(n^2), due to combination calculations. Space Complexity: O(n^2), used for the combination cache.

Try this approach in the editor β†’

Approach 3: Approach 1: DFS and Combinatorics

In this approach, think of the colony structure as a tree rooted at room 0. For each node (room), we can choose its children in any order as long as we ensure the order dictated by prevRoom. We use Depth-First Search (DFS) to explore this tree, calculating the number of ways we can construct the subtree rooted at each node while considering its children placement order using combinatorial principles. We employ a comb(n, k) approach, where n is the total number of nodes and k are the children nodes, to determine different permutations of building sequences taking into account already built sequences of other branches.

This Python solution defines the waysToBuildRooms method, which first sets up a tree based on the prevRoom relationships. It then performs a DFS traversal and calculates the number of ways to build the subtree from each node using combinatorics to account for different valid orderings of child nodes.

Code

Python

Java

C++

JavaScript

C#

Complexity

The time complexity is O(n log n) due to the combination calculations, and the space complexity is O(n) due to the recursion stack and storage of the tree structure.

Try this approach in the editor β†’

Approach 4: Approach 2: Topological Sort with Dynamic Programming

This approach leverages topological sorting to handle the sequential dependencies defined by prevRoom. Using dynamic programming, it calculates the number of ways to validly sequence room constructions such that all dependencies are respected. We calculate the result by processing nodes in topological order, ensuring all dependencies are met iteratively, hence constructing the final permutations.

In this Python solution, the tree is designed as an adjacency list based on prevRoom. It identifies all nodes with zero indegrees for topological processing. It then dynamically determines valid sequences, considering factorial-based permutations of child orderings, and adjusts based on dependencies, accumulating into dp[node].

Code

Python

C++

Complexity

The time complexity lies at O(n) due to the single traversal and computation using topological order, and the space complexity also holds at O(n) from storage of dependencies and intermediate states.

Try this approach in the editor β†’

Approach 5: Default Approach

Code

Python

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Dynamic Programming with Tree Representation

Time Complexity: O(n^2), where n is the number of rooms, due to combinations precomputation. Space Complexity: O(n^2) for the combination table to store computed values.

Combination Mathematics in Tree

Time Complexity: O(n^2), due to combination calculations. Space Complexity: O(n^2), used for the combination cache.

Approach 1: DFS and Combinatorics

The time complexity is O(n log n) due to the combination calculations, and the space complexity is O(n) due to the recursion stack and storage of the tree structure.

Approach 2: Topological Sort with Dynamic Programming

The time complexity lies at O(n) due to the single traversal and computation using topological order, and the space complexity also holds at O(n) from storage of dependencies and intermediate states.

Default Approachβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
DFS and CombinatoricsO(n)O(n)Best general solution; combines subtree sizes with multinomial coefficients
Dynamic Programming on TreeO(n)O(n)When implementing structured subtree DP with explicit states
Combination Mathematics in TreeO(n)O(n)When focusing on mathematical formulation of valid interleavings
Topological Sort with DPO(n)O(n)Useful for reasoning about dependency ordering in DAG-style problems

Video Solution

LeetCode 1916. Count Ways to Build Rooms in an Ant Colony β€’ Happy Coding β€’ 3,079 views views

Watch 3 more video solutions β†’

Frequently Asked Questions

Is Count Ways to Build Rooms in an Ant Colony easy or hard?
Count Ways to Build Rooms in an Ant Colony is classified as Hard. The challenge comes from recognizing that valid build sequences correspond to interleavings of independent subtrees and implementing the combinatorics efficiently with modular arithmetic.
Count Ways to Build Rooms in an Ant Colony Python/Java solution
Most implementations use DFS on the tree combined with factorial-based combination calculations under modulo. Python, Java, C++, and JavaScript versions follow the same structure: build adjacency lists, precompute factorials, run DFS, and combine subtree counts using multinomial coefficients.
How to solve Count Ways to Build Rooms in an Ant Colony in O(n)?
Build a tree from the parent array and run DFS from the root. For each node, calculate the number of nodes in its subtree and multiply child results while using combinations to interleave their build orders. Using precomputed factorials and inverse factorials allows all combinatorial calculations in constant time.
What is the best approach for Count Ways to Build Rooms in an Ant Colony?
DFS with combinatorics on the tree is the most efficient approach. Compute subtree sizes using DFS and count ways to interleave children using multinomial coefficients. Precomputing factorials and inverse factorials allows combination calculations in O(1), giving an overall O(n) solution.
Is Count Ways to Build Rooms in an Ant Colony asked at Google/Amazon/Meta?
Tree dynamic programming and combinatorics problems like this commonly appear in interviews at companies such as Google, Meta, and Amazon. The problem tests understanding of dependency graphs, subtree aggregation, and modular combinatorics.
What data structure is used in Count Ways to Build Rooms in an Ant Colony?
The core data structure is a tree represented with an adjacency list built from the parent array. The algorithm also uses arrays for factorials, inverse factorials, and subtree sizes to compute combinations efficiently.
What is the time complexity of Count Ways to Build Rooms in an Ant Colony?
The optimal solution runs in O(n) time. Each node is visited once during DFS, and combination values are computed using precomputed factorials and modular inverses. Space complexity is O(n) for the adjacency list, factorial arrays, and recursion stack.

Ready to solve this problem?

Practice Count Ways to Build Rooms in an Ant Colony with our built-in code editor and test cases.

Practice on FleetCode