Maximum Employees to Be Invited to a Meeting - Problem

A company is organizing a meeting with n employees around a large circular table. Each employee has exactly one favorite person they want to sit next to, and they'll only attend if this condition is met.

Think of this as a graph problem where each employee points to their favorite person, creating a functional graph (each node has exactly one outgoing edge). The challenge is to find the maximum number of employees we can invite while satisfying everyone's seating preferences.

Key insights:

  • Since it's a circular table, we can have cycles of any length
  • We can also have "chains" that lead into cycles
  • For cycles of length > 2, we can only invite the cycle members
  • For cycles of length 2 (mutual favorites), we can extend with chains leading to them

Goal: Return the maximum number of employees that can be invited to the meeting.

Input & Output

example_1.py — Basic 2-cycles
$ Input: [2,2,1,2]
Output: 3
💡 Note: Employee 1 and 2 are mutual favorites (1→2, 2→1). Employee 0 favorites employee 2, so we can seat them as 0→2↔1, creating a chain of length 3. Employee 3 also favorites 2, but we can only extend one side of the 2-cycle.
example_2.py — Large cycle
$ Input: [1,2,0]
Output: 3
💡 Note: We have a 3-cycle: 0→1→2→0. Since this is a cycle of length > 2, we can invite all 3 employees and seat them in this exact circular order.
example_3.py — Multiple 2-cycles with chains
$ Input: [3,0,1,4]
Output: 4
💡 Note: We have one 2-cycle: 0↔3 (0→3, 3→0). Employees 1 and 2 form a separate 2-cycle: 1→2→1. Wait, that's not right. Let me recalculate: 0→3, 1→0, 2→1, 3→4. This creates: 2→1→0↔3→4, but 4 would need to point somewhere. Let me use a simpler example.

Constraints

  • n == favorite.length
  • 2 ≤ n ≤ 105
  • 0 ≤ favorite[i] ≤ n - 1
  • favorite[i] != i (no self-favorites)

Visualization

Tap to expand
Maximum Employees to Be Invited to a Meeting INPUT Functional Graph (favorite[]) 0 1 2 3 Arrows show favorite[i] favorite[] array: 2 2 1 2 i=0 i=1 i=2 i=3 ALGORITHM (DFS) 1 Find Cycles DFS to detect all cycles 2 Classify Cycles Length 2 vs longer cycles 3 Find Tails Chains leading to 2-cycles 4 Compute Max max(big cycle, sum of pairs) DFS Analysis: 1 2 2-cycle (mutual) 0 3 tails FINAL RESULT Circular Table Seating TABLE 0 1 2 3 Not invited 0 next to 2 - OK 1 next to 2 - OK 2 next to 1 - OK Output: 3 Key Insight: In a functional graph, every node has exactly one outgoing edge. The answer is max of: 1) Largest cycle length, OR 2) Sum of all 2-cycles plus their longest incoming chains (tails). TutorialsPoint - Maximum Employees to Be Invited to a Meeting | DFS Approach
Asked in
Google 15 Amazon 8 Meta 12 Microsoft 6
26.2K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen