LeetCode 0886. Possible Bipartition Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0886. Possible Bipartition

Description

We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.

Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.

 

Example 1:

Input: n = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Explanation: The first group has [1,4], and the second group has [2,3].

Example 2:

Input: n = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false
Explanation: We need at least 3 groups to divide them. We cannot put them in two groups.

 

Constraints:

  • 1 <= n <= 2000
  • 0 <= dislikes.length <= 104
  • dislikes[i].length == 2
  • 1 <= ai < bi <= n
  • All the pairs of dislikes are unique.

Solutions

Solution 1

PythonJavaC++GoTypeScriptRust
class Solution: def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: def dfs(i, c): color[i] = c for j in g[i]: if color[j] == c: return False if color[j] == 0 and not dfs(j, 3 - c): return False return True g = defaultdict(list) color = [0] * n for a, b in dislikes: a, b = a - 1, b - 1 g[a].append(b) g[b].append(a) return all(c or dfs(i, 1) for i, c in enumerate(color))(code-box)

Solution 2

PythonJavaC++Go
class Solution: def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: def find(x): if p[x] != x: p[x] = find(p[x]) return p[x] g = defaultdict(list) for a, b in dislikes: a, b = a - 1, b - 1 g[a].append(b) g[b].append(a) p = list(range(n)) for i in range(n): for j in g[i]: if find(i) == find(j): return False p[find(j)] = find(g[i][0]) return True(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !