KatInterview

Split Nodes Into Two Groups With No Internal Links

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsgraphbfsbipartite

Last 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 is False whenever 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:

  • n is the number of nodes.
  • links is 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^5
  • 0 <= len(links) <= 2 * 10^5
  • 0 <= 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.