Skip to the content

The book club round

Problem

In Cleo's book club there is a single copy of the book of the month. Each member, when they finish it, always passes it on to the same member: they agreed on that when they signed up and nobody changes it. So the book ends up going round and round among a group of members, always in the same order, while the rest never see it again. Cleo wants to know how many members that group has.

Write a function that takes passes and start. passes is a dictionary where each key is the name of a member and its value is the name of the member they pass the book on to. Every member passes it on to somebody, and that somebody is always a member who is also a key of passes; a member can pass it on to themselves. start is the member who has the book at the beginning, and is also a key of passes. There are 1 to 20 members.

Return a whole number: how many members the round that the book repeats forever has. It is not how many members get to hold the book: the ones who hold it only once, before the round begins, do not go in that count. With {"Anna": "Ben", "Ben": "Clara", "Clara": "Dora", "Dora": "Ben"} and "Anna", the book goes Anna, Ben, Clara, Dora, Ben, Clara, Dora, and on and on without stopping. Anna had it just once; the three who keep getting it again are Ben, Clara and Dora, so you return 3. If the book reaches a member who passes it on to themselves, it stays there: the round has 1 member.

start can already be inside the round. If it is, nobody holds the book only once and the round is everybody who touches it.

Examples

  • The example

    {"Anna": "Ben", "Ben": "Clara", "Clara": "Dora", "Dora": "Ben"}, "Anna" → 3

  • Everybody is in the round

    {"Ivan": "Julia", "Julia": "Kara", "Kara": "Ivan"}, "Ivan" → 3

  • A member passes it on to himself

    {"Lucy": "Mark", "Mark": "Mark"}, "Lucy" → 1

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

You start with this

Python

def loop(passes, start):
    pass

JavaScript

function loop(passes, start) {
}
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(n) challenges

See all challenges →