Decide Whether an Undirected Graph Can Be Colored with Three Colors
SnowflakeSoftware Engineer · Technical ScreenLast updated
Given an undirected graph with up to fifteen nodes, decide whether every node can receive one of three colors so that no edge joins two nodes of the same color. It tests backtracking search with pruning and reasoning about odd cycles and cliques.
Given an undirected graph, decide whether every node can be given one of three colors so that no edge connects two nodes of the same color.
Function Signature
def can_three_color(n: int, edges: list[list[int]]) -> bool:
Rules
- The graph has
nnodes numbered0ton - 1, and each pair[a, b]inedgesis an undirected edge between nodesaandb. - Return
Trueif each node can be assigned one of three colors so that the two endpoints of every edge have different colors, andFalseotherwise. Not every color has to be used.
Constraints
1 <= n <= 150 <= len(edges) <= n * (n - 1) / 2- For every edge,
a != band both are between0andn - 1; no edge is listed twice, in either direction. - The graph does not have to be connected.
Examples
Example 1
Input: n = 4, edges = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]
Output: False
Every pair of the four nodes is connected, so all four need different colors.
Example 2
Input: n = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 0]]
Output: True
Two colors are not enough for a cycle of odd length, but three are: for example, colors 0, 1, 0, 1, 2 around the cycle.
Example 3
Input: n = 6, edges = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 0], [5, 0], [5, 1], [5, 2], [5, 3], [5, 4]]
Output: False
Node 5 touches all of nodes 0 to 4, so those five would have to share the two remaining colors, which is impossible around a cycle of odd length. No four nodes are all connected to one another, yet three colors still do not suffice.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.