980. Round Table Invites

A banquet hall has a single round table. There are n guests numbered 0 to n - 1. Guest i will only take a seat if their favourite person, favourite[i] (never i itself), is also at the table and sits in one of the two seats directly beside them. Many guests may share the same favourite.

You choose which guests to invite and how to arrange them around the circle (the first and last seats are neighbours; with only two guests each is the other's neighbour). Return the largest number of guests that can be seated so that every seated guest is happy.

Example 1

Input:
favourite = [1,2,3,0,0]
Output:
4
Explanation:

Guests 0, 1, 2, 3 form a loop where each one favours the next, so they can sit in that order around the table. Guest 4 favours 0, but both neighbours of 0 are already taken by 3 and 1, so the answer is 4.

Example 2

Input:
favourite = [1,0,0,2,3]
Output:
5
Explanation:

Guests 0 and 1 favour each other; guest 2 follows 0, guest 3 follows 2 and guest 4 follows 3. Seating 1, 0, 2, 3, 4 around the circle satisfies everyone, so all 5 fit.

Example 3

Input:
favourite = [1,0,3,2,5,4]
Output:
6
Explanation:

There are three separate mutual pairs. Each pair sits side by side and the pairs are placed one after another, so all 6 guests are seated.

Constraints

  • 2 ≤ favourite.length ≤ 105
  • 0 ≤ favourite[i] < favourite.length
  • favourite[i] ≠ i

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 800 msC++ 200 msJava 400 msJavaScript 400 msTypeScript 400 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…