#785
Is Graph Bipartite?
MediumDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryGraph Traversal (BFS, DFS)Coloring ProblemsUnion-Find
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + e) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + e)Space O(n)
The optimal solution uses BFS or DFS to color the graph in one pass, ensuring that no two adjacent nodes have the same color. This is efficient and leverages the properties of bipartite graphs.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a color array to track the color of each node.
- 2Step 2: For each uncolored node, start a BFS or DFS to color the graph.
- 3Step 3: If you find two adjacent nodes with the same color, return false. If all nodes are colored successfully, return true.
solution.py18 lines
1# Full working Python code
2from collections import deque
3
4def isBipartite(graph):
5 color = [-1] * len(graph)
6 for i in range(len(graph)):
7 if color[i] == -1:
8 queue = deque([i])
9 color[i] = 0
10 while queue:
11 node = queue.popleft()
12 for neighbor in graph[node]:
13 if color[neighbor] == -1:
14 color[neighbor] = 1 - color[node]
15 queue.append(neighbor)
16 elif color[neighbor] == color[node]:
17 return False
18 return Trueℹ
Complexity note: The time complexity is O(n + e) where n is the number of nodes and e is the number of edges, as we traverse each node and edge once. The space complexity is O(n) due to the color array.
- 1Bipartite graphs can be colored with two colors without adjacent nodes sharing the same color.
- 2Using BFS or DFS efficiently checks for bipartiteness in a single pass.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.