Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Can the graph be split in two?

Medium · Target 15 minutes · Graphs · Type asked atMetaAmazonGoogle

An undirected graph has n nodes numbered 0 to n − 1 and a list of edges. It may be disconnected. Return true if its nodes can be split into two sets so that every edge joins a node in one set to a node in the other, and false otherwise.

Examples

InputOutputWhy
n = 4, edges = [[0,1],[1,2],[2,3],[3,0]]trueA square: {0, 2} and {1, 3}.
n = 3, edges = [[0,1],[1,2],[2,0]]falseA triangle is an odd cycle.
n = 6, edges = [[0,1],[2,3],[3,4],[4,2]]falseThe first part is fine; the triangle 2–3–4 is not.

Constraints

  • 1 ≤ n ≤ 10⁴
  • 0 ≤ edges.length ≤ 2 · 10⁴
  • No self-loops or repeated edges

Hints

Hint 1

Colour the first node A. Its neighbours are then forced to be B, their neighbours A, and so on.

Hint 2

Run that forced colouring as a breadth-first search. If an edge ever joins two nodes of the same colour, return false.

Hint 3

The graph may be disconnected: start a new search from every node that is still uncoloured.

Where people lose marks

  • Checking only the piece that contains node 0.
  • Treating "visited" and "colour" separately and forgetting to compare colours on edges to visited nodes.
  • Using recursion on a long path of 10⁴ nodes in Python.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.