Graph traversal · Medium
A scheduler wants to divide services into two groups. Each undirected edge says that its endpoints must belong to different groups. Disconnected services and disconnected conflict clusters must all be considered.
Return whether all n services can be assigned to two groups while satisfying every conflict edge.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "n": number, "edges": [number,number][] }.
Fields
- n is the number of vertices with IDs 0..n-1. Every endpoint is valid. Parallel edges and self-edges are allowed; when n is 0 the edge list is empty.
- edges contains undirected [first,second] conflict pairs.
Output
Return value
- Return a boolean; the actual grouping is not required.
- A self-edge is impossible. Repeated edges do not add a new constraint.
- An empty graph and isolated vertices can be split successfully.
Constraints
- 0 <= n <= 100000 and at most 200000 edges.
- A chain may contain 100000 vertices; do not depend on a call stack that deep.
Examples
Example 1
{
"edges": [
[
0,
1
],
[
1,
2
],
[
2,
0
]
],
"n": 3
}Returns
falseA triangle needs more than two groups.
Example 2
{
"edges": [
[
0,
1
],
[
2,
3
]
],
"n": 4
}Returns
trueBoth independent pairs can be split.
Required complexity
O(n + m) time and space