Skip to content
Decoder

Is Graph Bipartite?

Medium

Problem

You get an undirected graph as an adjacency list: graph[u] lists the neighbours of node u. The graph may not be connected. Return true if you can split the nodes into two groups so that every edge joins nodes from different groups, and false otherwise.

Example 1

Input
graph = [[1, 3], [0, 2], [1, 3], [0, 2]]
Output
true
Why
groups {0, 2} and {1, 3}

Example 2

Input
graph = [[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]]
Output
false
Why
0, 1, 2 form a triangle

Constraints

  • 1 <= graph.length <= 100
  • 0 <= graph[u].length < graph.length
  • No self-loops, no repeated neighbours, and if v is in graph[u] then u is in graph[v]

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.