Count Ways to Build Rooms in an Ant Colony — LeetCode 1916 Python Solution

HardTreeGraphTopological SortMathDynamic ProgrammingCombinatorics
Problem
#1916
Reading time
5 min

The 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.

Example

Input
prevRoom = [-1,0,1]
Output
1
Explanation
There is only one way to build the additional rooms: 0 → 1 → 2

Python solution

Python
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

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Topological Sort

Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 1916. Count Ways to Build Rooms in an Ant Colony is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.

The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1916. Count Ways to Build Rooms in an Ant Colony?
LeetCode 1916. Count Ways to Build Rooms in an Ant Colony is rated Hard on LeetCode.
What topics does LeetCode 1916. Count Ways to Build Rooms in an Ant Colony cover?
LeetCode 1916. Count Ways to Build Rooms in an Ant Colony is tagged Tree, Graph, Topological Sort, Math, Dynamic Programming and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview