Split Nodes Into Two Groups With No Internal Links
Trees & GraphsAuto-graded · 21 test casesLast updated
Decide whether the vertices of an undirected multigraph can be split into two groups so every edge crosses between them, handling self-loops, repeated edges, and isolated nodes.
Two Groups, No Internal Links
You have a network of n nodes numbered 0 through n - 1. The links between nodes are given as a list links, where each entry [a, b] describes an undirected link joining node a and node b.
You want to split the nodes into two groups, called group 0 and group 1, so that every link joins one node from each group. In other words, no link may have both endpoints in the same group. Every node must be placed in exactly one group.
Return True if such a split exists, and False otherwise.
Details to watch for
- The network may consist of several separate pieces, and each piece must be checked.
- Some nodes may have no links at all. They can go in either group and never cause a problem.
- A link may connect a node to itself (
a == b). Such a link can never join two different groups, so the answer isFalsewhenever one exists. - The same pair of nodes may be linked more than once. Repeated links do not change the answer.
Function
Implement can_split_into_two_groups(n, links), where:
nis the number of nodes.linksis a list of[a, b]pairs describing undirected links.
It returns a boolean: True if a valid split exists, False otherwise.
Constraints
1 <= n <= 10^50 <= len(links) <= 2 * 10^50 <= links[i][0], links[i][1] < n- Very long chains of nodes are possible, so avoid solutions that rely on deep recursion.
Examples
Example 1
Input: can_split_into_two_groups(4, [[0, 1], [1, 2], [2, 3], [3, 0]])
Output: True
Example 2
Input: can_split_into_two_groups(3, [[0, 1], [1, 2], [2, 0]])
Output: False
Example 3
Input: can_split_into_two_groups(4, [[0, 1], [1, 1]])
Output: False
Hints
Hint 1
A valid split exists exactly when you can label nodes with 0 or 1 so that every link connects different labels. Once one node in a connected piece is labeled, every other label in that piece is forced.
Hint 2
Start a breadth-first search from every node that has not been labeled yet, not only from node 0, so that separate pieces and isolated nodes are all covered.
Hint 3
While exploring, give each newly found neighbor the opposite label. If you meet an already-labeled neighbor with the same label as the current node, the answer is False. A self-loop triggers this automatically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A valid split exists exactly when the graph has no cycle of odd length. Instead of hunting for cycles, we try to build the split directly.
- Build an adjacency list. A self-loop
[v, v]simply putsvin its own neighbor list; repeated links just repeat entries. - Keep an array
groupinitialized to-1(unassigned). - For every node not yet assigned, put it in group 0 and run a BFS from it with an explicit queue.
- When BFS discovers an unassigned neighbor, give it the opposite group of the current node.
- If a neighbor is already assigned the same group as the current node, return
False. - If every piece finishes without conflict, return
True.
Why it is correct
- Forced labels: inside one connected piece, fixing the start node's group forces every other node's group (a node at BFS distance
dmust getd mod 2). Choosing 0 for the start loses nothing, since the only alternative is the mirror image. - Conflict implies impossible: if a link joins two nodes with the same group, their BFS depths have the same parity. The tree paths from both nodes to their common ancestor plus this link form a closed walk of odd length, which contains an odd cycle, so no valid split exists.
- No conflict implies valid: BFS inspects every link from both endpoints, so if no conflict was found, all links join different groups.
- Separate pieces are independent: the outer loop over all nodes handles disconnected graphs and isolated nodes (they get group 0 and their BFS ends immediately).
- Self-loops: the node sees itself as a neighbor with the same group, so
Falseis returned. Repeated links are re-checked harmlessly. - Deep chains: BFS uses a queue rather than recursion, so there is no recursion-depth problem.
Complexity
- Time:
O(n + m), wherem = len(links). - Space:
O(n + m)for the adjacency list, group array, and queue.
Reference solution
from collections import deque
from typing import List
def can_split_into_two_groups(n: int, links: List[List[int]]) -> bool:
adj = [[] for _ in range(n)]
for a, b in links:
adj[a].append(b)
adj[b].append(a)
group = [-1] * n # -1 means not yet assigned
for s in range(n):
if group[s] != -1:
continue
group[s] = 0
q = deque([s])
while q:
cur = q.popleft()
for nxt in adj[cur]:
if group[nxt] == -1:
group[nxt] = 1 - group[cur]
q.append(nxt)
elif group[nxt] == group[cur]:
return False
return True