FastPrepPossible Bipartition

Possible Bipartition

ByteDance logoByteDance● MediumFULLTIMEPHONE SCREEN

Problem statement

There are n people labeled from 1 through n. Each pair [a, b] in dislikes means those two people must be in different groups.

Return true if everyone can be assigned to one of two groups while satisfying every dislike pair; otherwise return false. The groups may have any sizes. A pair imposes the same restriction in both directions.

The people need not form a connected graph. Your algorithm must check every component, including people not connected to person 1.

Function

possibleBipartition(n: int, dislikes: int[][]) → boolean

Examples

Example 1

n = 6dislikes = [[1,2],[2,3],[4,5]]return = true

Groups {1,3,4,6} and {2,5} satisfy every dislike.

Example 2

n = 4dislikes = [[1,2],[1,3],[2,3]]return = false

The three mutually connected people cannot use two opposite groups.

Example 3

n = 1dislikes = []return = true

There are no conflicting pairs; group sizes may differ and one group may be empty.

Constraints

  • 1 <= n <= 2000.
  • 0 <= dislikes.length <= 10000.
  • Every pair contains two labels with 1 <= a < b <= n.
  • All dislike pairs are distinct.

More ByteDance problems

See ByteDance hiring insights
Saved
public boolean possibleBipartition(int n, int[][] dislikes) {
    // write your code here
}
n6
dislikes[[1,2],[2,3],[4,5]]
expectedtrue
Checking account…