Is Graph Bipartite

Medium

This is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.

Question

You're given an undirected network of nodes. The list graph[u] holds every node directly connected to node u.

Return whether you can split the nodes into two camps so that every connection joins nodes from different camps. A connection is never allowed to join two nodes in the same camp.

Input: graph = [[1, 3], [0, 2], [1, 3], [0, 2]]

Output: True

Put nodes 0 and 2 in one camp and nodes 1 and 3 in the other. Every connection crosses between the two camps.

Input: graph = [[1, 2], [0, 2], [0, 1]]

Output: False

Every node here connects to both of the others. Nodes 1 and 2 have to go in the other camp from node 0. But nodes 1 and 2 also connect to each other. That means they'd need to be in different camps from each other too. You can't do that with only two camps.

Input: graph = [[1], [0], [3], [2]]

Output: True

This network has two separate pieces (0-1 and 2-3). You can split each piece into two camps on its own.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

Can this network be split into two camps? graph = [[1, 4], [0, 2], [1, 3], [2, 4], [3, 0]]
No
Yes
Only if node 0 is placed alone in its own camp
Not enough information

Remember to understand the problem and plan your approach before you start coding.