Q&A-17How do you determine if a graph is bipartite using BFS or DFS, and at what threshold does graph coloring become NP-complete?
Answer
Determining whether an undirected graph is bipartite is identical to asking whether it is 2-colorable: can every vertex be assigned one of two colors such that no adjacent vertices share a color? This is solvable in linear time, $O(V + E)$, using BFS or DFS. In contrast, deciding $k$-colorability is NP-complete for any fixed $k \ge 3$ on general graphs.
Bipartite Verification Mechanism
A graph is bipartite if and only if it contains no odd-length cycles. We verify this by 2-coloring each connected component:
- Maintain a
colorarray indexed by vertex, initialized to an unvisited state (e.g.,-1). - Iterate through all vertices $0$ to $V-1$. If vertex $i$ is unvisited, assign
color[i] = 0and launch a BFS or DFS traversal. - For each visited vertex $u$ with color $c$, examine every neighbor $v$:
- If $v$ is unvisited, assign
color[v] = 1 - cand push $v$ to the queue/stack. - If $v$ is already visited and
color[v] == color[u], an odd-length cycle exists; terminate immediately and returnFalse.
- If $v$ is unvisited, assign
- If all components are colored without conflicts, the graph is bipartite and the 2-coloring is valid.
from collections import deque
def is_bipartite(graph: list[list[int]]) -> bool:
n = len(graph)
color = [-1] * n
for start in range(n):
if color[start] != -1:
continue
color[start] = 0
queue = deque([start])
while queue:
u = queue.popleft()
for v in graph[u]:
if color[v] == -1:
color[v] = 1 - color[u]
queue.append(v)
elif color[v] == color[u]:
# Found an odd cycle (u and v share the same layer parity)
return False
return TrueThe Complexity Boundary
- $k = 1$: Trivial. Graph must contain zero edges ($O(V + E)$).
- $k = 2$: Linear time ($O(V + E)$) via BFS/DFS 2-coloring.
- $k \ge 3$: NP-complete. 3-coloring is one of Karp's original NP-complete problems (reducible from 3-SAT). Even on planar graphs with maximum vertex degree 4, 3-coloring remains NP-complete.
Common Pitfalls and Failure Modes
- Disconnected Components: Forgetting the outer loop over all vertices leaves disconnected components unvisited, returning a false positive when an unvisited component contains an odd cycle.
- Recursion Limit with DFS: In deep graphs (e.g., a path graph with $V = 10^5$), standard DFS hits Python's default recursion limit (
sys.getrecursionlimit() = 1000), raisingRecursionError. BFS or iterative DFS avoids this entirely.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.