Possible Bipartition

There are `n` people labeled `1` to `n`. `dislikes[i] = [a_i, b_i]` means person `a_i` and person `b_i` dislike each other and cannot be in the same group. Return `true` if everyone can be split into two groups (of any size) so that no group holds two people who dislike each other, and `false` otherwise.

30:00

Possible Bipartition
medium
Free written solution
Topics
Companies

There are n people labeled 1 to n. dislikes[i] = [a_i, b_i] means person a_i and person b_i dislike each other and cannot be in the same group. Return true if everyone can be split into two groups (of any size) so that no group holds two people who dislike each other, and false otherwise.

Example 1:
Input: {"n":4,"dislikes":[[1,2],[1,3],[2,4]]}
Output: true
Constraints:
  • 1≤n≤20001 \leq n \leq 2000

  • 0≤dislikes.length≤1040 \leq \text{dislikes.length} \leq 10^4

  • dislikes[i].length==2\text{dislikes}[i].\text{length} == 2

  • 1≤ai<bi≤n1 \leq a_i < b_i \leq n

  • All the pairs of dislikes\text{dislikes} are unique

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":4,"dislikes":[[1,2],[1,3],[2,4]]}

Turn the 3 dislike pairs into an adjacency list. Every dislike must end up crossing between group A and group B.

dislikes must cross between the groups

GROUP ANOT PLACEDGROUP B1234

BFS queue

empty

BFS starts

0

answer

...

Variables
VariableValue
n4
dislikes3
DepthFunction Call
Stack empty
0/12