Maximum Employees to Be Invited to a Meeting
Maximum Employees to Be Invited to a Meeting is a hard graphs problem solved with the topological sort pattern.
The best approach, optimal (peel with a topological sort, then measure the loops), runs in O(n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from walk from every employee up.
Problem
A company is planning a meeting and has a list of n employees, numbered from 0 to n - 1, waiting to be invited. The meeting takes place at a large round table that can seat any number of people.
Every employee has exactly one favorite colleague, and it is never themselves. They will only come to the meeting if they can sit right next to that favorite person, on either side. Liking does not have to be mutual: the favorite person may like someone else.
You are given an integer array favorite of length n, where favorite[i] is the favorite colleague of employee i. Return the largest number of employees that can be invited so that every one of them sits next to their favorite person.
Examples
Example 1
- Input
favorite = [1,2,3,1,1]- Output
3- Why
- Employees 1, 2 and 3 like each other in a loop: 1 likes 2, 2 likes 3 and 3 likes 1. Seating them around the table puts everyone next to the person they like. Employees 0 and 4 both like 1, but 1 already has both neighbours taken by 2 and 3, so neither of them can join.
Example 2
- Input
favorite = [1,0,1,2,0,6,5,5,9,10,11,8]- Output
8- Why
- Employees 0 and 1 like each other, and so do 5 and 6. Such a mutual pair can take a whole line of fans with it: 3 likes 2, who likes 1, and 4 likes 0, giving the row 3, 2, 1, 0, 4. The pair 5 and 6 brings 7 along: 5, 6, 7. Both rows fit at the same table, for 5 + 3 = 8 people. The loop 8, 9, 10, 11 only gives 4.
Example 3
- Input
favorite = [1,2,3,4,0,0]- Output
5- Why
- Employees 0 to 4 form a loop of five, and the whole loop can sit together. Employee 5 likes 0, but 0 is already surrounded by 4 and 1, so 5 stays home.
Constraints
n == favorite.length2 <= n <= 10^50 <= favorite[i] <= n - 1favorite[i] != i
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Walk from every employee | O(n²) | O(n) |
| Optimal (peel with a topological sort, then measure the loops) | O(n) | O(n) |
1Walk from every employee
O(n²)Each of the n walks can be as long as the whole graph, for example when everyone forms one long line into a pair.O(n)Two arrays of n integers, the step marks and the longest lines.Start at each employee and follow the favorite arrows, numbering the steps, until a person is reached for the second time. That person is the first one on the loop the walk falls into, and the step numbers give both the loop length and how many people came before the loop. A loop of three or more is a candidate on its own. When the loop has length two, the people before it form a line of fans ending at the loop person we hit, so we keep the longest such line for every person. At the end, every mutual pair contributes 2 plus the longest line into each of its two people, and all pairs can sit together.
- stepAt[n] filled with -1; arm[n] = 0 holds the longest line of fans that ends at a person on a 2-loop; longestCycle = 0.
- For each start: follow favorite from start, setting stepAt[cur] = step, until stepAt[cur] is already set.
- tail = stepAt[cur] is the number of people before the loop; cycleLen = step - tail.
- If cycleLen is 2, set arm[cur] = max(arm[cur], tail); otherwise longestCycle = max(longestCycle, cycleLen).
- Walk the same path again to clear stepAt for the next start.
- For every pair i < j with favorite[i] = j and favorite[j] = i, add 2 + arm[i] + arm[j] to pairs.
- Return max(longestCycle, pairs).
class Solution {
public int maximumInvitations(int[] favorite) {
int n = favorite.length;
int[] stepAt = new int[n];
Arrays.fill(stepAt, -1);
int[] arm = new int[n];
int longestCycle = 0;
for (int start = 0; start < n; start++) {
int cur = start, step = 0;
while (stepAt[cur] == -1) {
stepAt[cur] = step++;
cur = favorite[cur];
}
int tail = stepAt[cur];
int cycleLen = step - tail;
if (cycleLen == 2) arm[cur] = Math.max(arm[cur], tail);
else longestCycle = Math.max(longestCycle, cycleLen);
for (int x = start, k = 0; k < step; k++, x = favorite[x]) stepAt[x] = -1;
}
int pairs = 0;
for (int i = 0; i < n; i++) {
int j = favorite[i];
if (i < j && favorite[j] == i) pairs += 2 + arm[i] + arm[j];
}
return Math.max(longestCycle, pairs);
}
}class Solution:
def maximumInvitations(self, favorite: List[int]) -> int:
n = len(favorite)
step_at = [-1] * n
arm = [0] * n
longest_cycle = 0
for start in range(n):
cur, step = start, 0
while step_at[cur] == -1:
step_at[cur] = step
step += 1
cur = favorite[cur]
tail = step_at[cur]
cycle_len = step - tail
if cycle_len == 2:
arm[cur] = max(arm[cur], tail)
else:
longest_cycle = max(longest_cycle, cycle_len)
x = start
for _ in range(step):
step_at[x] = -1
x = favorite[x]
pairs = 0
for i in range(n):
j = favorite[i]
if i < j and favorite[j] == i:
pairs += 2 + arm[i] + arm[j]
return max(longest_cycle, pairs)class Solution {
public:
int maximumInvitations(vector<int>& favorite) {
int n = favorite.size();
vector<int> stepAt(n, -1);
vector<int> arm(n, 0);
int longestCycle = 0;
for (int start = 0; start < n; start++) {
int cur = start, step = 0;
while (stepAt[cur] == -1) {
stepAt[cur] = step++;
cur = favorite[cur];
}
int tail = stepAt[cur];
int cycleLen = step - tail;
if (cycleLen == 2) arm[cur] = max(arm[cur], tail);
else longestCycle = max(longestCycle, cycleLen);
for (int x = start, k = 0; k < step; k++, x = favorite[x]) stepAt[x] = -1;
}
int pairs = 0;
for (int i = 0; i < n; i++) {
int j = favorite[i];
if (i < j && favorite[j] == i) pairs += 2 + arm[i] + arm[j];
}
return max(longestCycle, pairs);
}
};function maximumInvitations(favorite) {
const n = favorite.length;
const stepAt = new Array(n).fill(-1);
const arm = new Array(n).fill(0);
let longestCycle = 0;
for (let start = 0; start < n; start++) {
let cur = start, step = 0;
while (stepAt[cur] === -1) {
stepAt[cur] = step++;
cur = favorite[cur];
}
const tail = stepAt[cur];
const cycleLen = step - tail;
if (cycleLen === 2) arm[cur] = Math.max(arm[cur], tail);
else longestCycle = Math.max(longestCycle, cycleLen);
for (let x = start, k = 0; k < step; k++, x = favorite[x]) stepAt[x] = -1;
}
let pairs = 0;
for (let i = 0; i < n; i++) {
const j = favorite[i];
if (i < j && favorite[j] === i) pairs += 2 + arm[i] + arm[j];
}
return Math.max(longestCycle, pairs);
}2Optimal (peel with a topological sort, then measure the loops)
O(n)Each person is pushed and popped at most once while peeling, and each loop person is visited once while measuring loops.O(n)The in-degree and depth arrays plus the queue, each up to n entries.Every employee has one outgoing arrow, so each piece of the graph is a single loop with trees of fans hanging into it. People that nobody likes can never be on a loop, so remove them first, like a topological sort with in-degrees: put every person with in-degree 0 in a queue, and when you remove u, lower the in-degree of favorite[u], pushing it once it reaches 0. While peeling, carry depth: depth[v] is the number of people in the longest line that ends at v, v included. Whatever survives the peeling lies on loops. Walk each loop once to measure it. A loop of three or more is a candidate by itself. A loop of two, i and favorite[i], gives depth[i] + depth[favorite[i]] people, and all such pairs add up because they can share the table.
- indeg[v] = how many people like v. depth[v] = 1 for everyone.
- Queue every person with indeg 0.
- Pop u, let v = favorite[u]: depth[v] = max(depth[v], depth[u] + 1); decrease indeg[v] and push v when it hits 0.
- Every person with indeg still above 0 is on a loop. For each such i, walk the loop from i, setting indeg to 0 and counting its length.
- If the length is 2, add depth[i] + depth[favorite[i]] to pairs; otherwise longestCycle = max(longestCycle, length).
- Return max(longestCycle, pairs).
class Solution {
public int maximumInvitations(int[] favorite) {
int n = favorite.length;
int[] indeg = new int[n];
for (int f : favorite) indeg[f]++;
int[] depth = new int[n];
Arrays.fill(depth, 1);
ArrayDeque<Integer> queue = new ArrayDeque<>();
for (int i = 0; i < n; i++) if (indeg[i] == 0) queue.add(i);
while (!queue.isEmpty()) {
int u = queue.poll();
int v = favorite[u];
depth[v] = Math.max(depth[v], depth[u] + 1);
if (--indeg[v] == 0) queue.add(v);
}
int longestCycle = 0, pairs = 0;
for (int i = 0; i < n; i++) {
if (indeg[i] == 0) continue;
int len = 0;
for (int x = i; indeg[x] != 0; x = favorite[x]) {
indeg[x] = 0;
len++;
}
if (len == 2) pairs += depth[i] + depth[favorite[i]];
else longestCycle = Math.max(longestCycle, len);
}
return Math.max(longestCycle, pairs);
}
}class Solution:
def maximumInvitations(self, favorite: List[int]) -> int:
n = len(favorite)
indeg = [0] * n
for f in favorite:
indeg[f] += 1
depth = [1] * n
queue = deque(i for i in range(n) if indeg[i] == 0)
while queue:
u = queue.popleft()
v = favorite[u]
depth[v] = max(depth[v], depth[u] + 1)
indeg[v] -= 1
if indeg[v] == 0:
queue.append(v)
longest_cycle, pairs = 0, 0
for i in range(n):
if indeg[i] == 0:
continue
length = 0
x = i
while indeg[x] != 0:
indeg[x] = 0
length += 1
x = favorite[x]
if length == 2:
pairs += depth[i] + depth[favorite[i]]
else:
longest_cycle = max(longest_cycle, length)
return max(longest_cycle, pairs)class Solution {
public:
int maximumInvitations(vector<int>& favorite) {
int n = favorite.size();
vector<int> indeg(n, 0);
for (int f : favorite) indeg[f]++;
vector<int> depth(n, 1);
queue<int> q;
for (int i = 0; i < n; i++) if (indeg[i] == 0) q.push(i);
while (!q.empty()) {
int u = q.front();
q.pop();
int v = favorite[u];
depth[v] = max(depth[v], depth[u] + 1);
if (--indeg[v] == 0) q.push(v);
}
int longestCycle = 0, pairs = 0;
for (int i = 0; i < n; i++) {
if (indeg[i] == 0) continue;
int len = 0;
for (int x = i; indeg[x] != 0; x = favorite[x]) {
indeg[x] = 0;
len++;
}
if (len == 2) pairs += depth[i] + depth[favorite[i]];
else longestCycle = max(longestCycle, len);
}
return max(longestCycle, pairs);
}
};function maximumInvitations(favorite) {
const n = favorite.length;
const indeg = new Array(n).fill(0);
for (const f of favorite) indeg[f]++;
const depth = new Array(n).fill(1);
const queue = [];
for (let i = 0; i < n; i++) if (indeg[i] === 0) queue.push(i);
for (let head = 0; head < queue.length; head++) {
const u = queue[head];
const v = favorite[u];
depth[v] = Math.max(depth[v], depth[u] + 1);
if (--indeg[v] === 0) queue.push(v);
}
let longestCycle = 0, pairs = 0;
for (let i = 0; i < n; i++) {
if (indeg[i] === 0) continue;
let len = 0;
for (let x = i; indeg[x] !== 0; x = favorite[x]) {
indeg[x] = 0;
len++;
}
if (len === 2) pairs += depth[i] + depth[favorite[i]];
else longestCycle = Math.max(longestCycle, len);
}
return Math.max(longestCycle, pairs);
}Edge cases to test
- n = 2: the two employees always like each other, answer 2
- One big loop through everyone: the answer is n
- Only mutual pairs, each with long lines of fans: the answer adds up every pair with its two longest lines
- A mutual pair beats a longer loop only when its fans make it longer (compare the loop with the SUM of all pairs)
- Many fans point at the same person: only the longest line into each end of a pair counts
- A loop of three or more never takes any fans, no matter how many point into it
Hints
Hint 1
Draw an arrow from each employee to the person they like. Every employee has exactly one outgoing arrow. What shapes can such a graph have?
Hint 2
Each connected piece is one loop with trees of people hanging into it. Which loops can sit at a round table on their own, and can anyone else join them?
Hint 3
A loop of length three or more fills the table by itself. A loop of length two (two people who like each other) is different: each of the two still has a free side, so a line of fans can extend from each one.
Hint 4
Several mutual pairs, each with their lines, can all sit at one table side by side. The answer is the larger of the longest loop and the total over all pairs.
Hint 5
To get the longest line of fans into every node in linear time, peel the graph from the outside with a topological sort (people nobody likes first) and carry a depth along.
FAQ
What is the best time complexity for Maximum Employees to Be Invited to a Meeting?
Optimal (peel with a topological sort, then measure the loops) runs in O(n) time and O(n) extra space. Each person is pushed and popped at most once while peeling, and each loop person is visited once while measuring loops.
Which pattern does Maximum Employees to Be Invited to a Meeting use?
It is a graphs problem that uses the topological sort pattern. Other problems with the same pattern: Topological sort using BFS, Course Schedule, Course Schedule II.
Is there a brute force solution for Maximum Employees to Be Invited to a Meeting?
Yes. Walk from every employee takes O(n²) time and O(n) space. Start at each employee and follow the favorite arrows, numbering the steps, until a person is reached for the second time.
Which edge cases should I test for Maximum Employees to Be Invited to a Meeting?
n = 2: the two employees always like each other, answer 2; One big loop through everyone: the answer is n; Only mutual pairs, each with long lines of fans: the answer adds up every pair with its two longest lines; A mutual pair beats a longer loop only when its fans make it longer (compare the loop with the SUM of all pairs); Many fans point at the same person: only the longest line into each end of a pair counts; A loop of three or more never takes any fans, no matter how many point into it.