Possible Bipartition

MediumGraphsbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n people numbered 1 through n. You want to split all of them into two groups (either group may be empty). Some pairs of people refuse to be in the same group: dislikes[i] = [a, b] means person a and person b must end up in different groups. Return true if such a split exists, and false otherwise. Each dislike pair is listed at most once and always has a < b.

Examples

Input: n = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Put `{1,4}` in one group and `{2,3}` in the other.
Input: n = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false
The three people all dislike each other, forming an odd cycle, so two groups cannot separate every pair.

Constraints

  • 1 <= n <= 2000
  • 0 <= dislikes.length <= 10^4
  • `dislikes[i].length == 2`
  • 1 <= a < b <= n
  • All pairs in `dislikes` are unique

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems