Skip to the content

The houses of Xibalba

Problem

In the Popol Vuh, the lords of Xibalba put the twins Hunahpu and Xbalanque to the test: they have to spend one night in each of their houses, the Dark House, the Cold House, the Jaguar House and the rest. The twins pick the order, but some houses only open once they have been through certain others. Before going in, they want to know how many ways they have.

The houses are numbered from 0. You get before, a list with one list per house: before[i] holds the numbers of the houses they must have visited before entering house i, at any earlier point, not necessarily right before. It may be empty and it never includes i.

Return, as a whole number, how many different orders there are to visit every house, each one exactly once, without breaking any requirement. With [[], [], [0]] house 2 needs house 0, and 0, 1, 2; 1, 0, 2 and 0, 2, 1 all work: you return 3. With [[], [0], [0], [1, 2]] house 0 goes first and house 3 goes last, with 1 and 2 in between in either order: you return 2.

If the requirements contradict each other and there is no way to visit them all, return 0. If there are no houses, there is exactly one order, the one that enters none: return 1.

Examples

  • The first example

    [[], [], [0]] → 3

  • The second example

    [[], [0], [0], [1, 2]] → 2

  • Only one possible order

    [[], [0], [1], [2]] → 1

  • No requirements

    [[], [], [], []] → 24

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def orderings(before):
    pass

JavaScript

function orderings(before) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(2ⁿ) challenges

See all challenges →