1517. Peace Holds Until
A summit has n delegates numbered 0 to n - 1. Rivalries are announced one at a time: edges[i] = [u, v] means delegates u and v become rivals on day i + 1. Rivalries are never withdrawn, and the same pair may be announced more than once. A delegate can also be listed as a rival of themself.
The organisers can keep the summit peaceful only while the delegates can be split into two tables so that no two rivals sit together. Return the largest p between 0 and edges.length such that the first p announced rivalries still allow such a split. A rivalry of a delegate with themself makes the split impossible. The property only gets worse as edges are added, so you could binary search p with an iterative BFS 2-colouring, but a single pass of a parity union-find finds the first breaking edge directly. Aim for O((n + m) alpha) time and O(n) space; avoid recursion.
Example 1
- Input:
- n = 4, edges = [[0,1],[1,2],[2,3],[3,0],[0,2]]
- Output:
- 4
- Explanation:
The first four edges form an even cycle, which is splittable, but the fifth edge closes a triangle, so the answer is 4.
Example 2
- Input:
- n = 3, edges = []
- Output:
- 0
- Explanation:
With no rivalries there is nothing to break, so p is 0.
Example 3
- Input:
- n = 3, edges = [[0,1],[1,1],[1,2]]
- Output:
- 1
- Explanation:
The second edge is a delegate rival to themself, so only the first edge can be kept.
Constraints
1 ≤ n ≤ 105
0 ≤ edges.length ≤ 2 * 105
0 ≤ u, v < n; repeated edges are allowed; use an iterative BFS or find (no deep recursion)
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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O((n + m) * alpha(n))
- Space
- O(n)