#886
Possible Bipartition
MediumDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryGraph TheoryBipartite GraphsBreadth-First Search (BFS)Depth-First Search (DFS)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + m)Space O(n)
The optimal solution uses graph theory to represent the problem as a bipartite graph. We can check if the graph can be colored with two colors, where adjacent nodes (people who dislike each other) have different colors.
⚙️
Algorithm
4 steps- 1Step 1: Create an adjacency list from the dislikes array to represent the graph.
- 2Step 2: Initialize a color array to keep track of the color assigned to each person.
- 3Step 3: For each person, if not colored, perform a BFS or DFS to color the graph. Assign one color to the person and the opposite color to their neighbors.
- 4Step 4: If a conflict arises (two adjacent nodes have the same color), return false. If all nodes are colored successfully, return true.
solution.py22 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def possible_bipartition(n, dislikes):
5 graph = defaultdict(list)
6 for a, b in dislikes:
7 graph[a].append(b)
8 graph[b].append(a)
9 color = [0] * (n + 1)
10 for person in range(1, n + 1):
11 if color[person] == 0:
12 queue = deque([person])
13 color[person] = 1
14 while queue:
15 current = queue.popleft()
16 for neighbor in graph[current]:
17 if color[neighbor] == 0:
18 color[neighbor] = -color[current]
19 queue.append(neighbor)
20 elif color[neighbor] == color[current]:
21 return False
22 return Trueℹ
Complexity note: This complexity is due to traversing the graph with n nodes and m edges, which is efficient for this problem size.
- 1Understanding how to represent relationships as a graph is crucial for solving bipartition problems.
- 2Using BFS or DFS to color the graph helps identify conflicts quickly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.