679. Rival Groups
At a summer camp, n campers are labelled 1 to n. The list dislikes contains pairs [a, b] meaning campers a and b refuse to be in the same group (the feeling is mutual). The counsellors want to divide all campers into two groups, either of which may be empty, so that no pair from the list ends up together.
Return true if such a division exists, otherwise false. A pair may appear more than once, a pair [a, a] makes the split impossible, and the same camper may appear in many pairs. Campers with no pair can go anywhere. Aim for O(n + m) time and O(n + m) space, where m is the number of pairs, and use an iterative traversal.
Example 1
- Input:
- n = 5, dislikes = [[1,2],[3,4],[2,3]]
- Output:
- true
- Explanation:
Groups {1, 3} and {2, 4} separate every disliked pair, so the answer is true.
Example 2
- Input:
- n = 6, dislikes = [[1,4],[4,6],[6,1],[2,5]]
- Output:
- false
- Explanation:
Campers 1, 4 and 6 dislike each other in a triangle, so no two-group split can keep them all apart.
Constraints
1 ≤ n ≤ 100000
0 ≤ dislikes.length ≤ 200000
1 ≤ a, b ≤ n; pairs may repeat, and a pair with a == b means a camper dislikes themself
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n + m)
- Space
- O(n + m)