![]() |
VOOZH | about |
Given a group of n people labeled from 1 to n, the task is to split them into two groups of any size such that no two people who dislike each other are in the same group. The input consists of the integer n and an array dislikes[] where each element [ai, bi] indicates that the person labeled ai dislikes the person labeled bi. The task is to return true if it is possible to split the people into two groups in this way, and false otherwise.
Examples:
Input: n = 4, dislikes = [[1, 2], [1, 3], [2, 4]]
Output: true
Explanation: The first group can have [1, 4], and the second group can have [2, 3].Input: n = 3, dislikes = [[1, 2], [1, 3], [2, 3]]
Output: false
Explanation: We need at least 3 groups to divide them because person 1 dislikes both 2 and 3, and person 2 and 3 dislike each other.
The problem can be viewed as a graph coloring problem where each person represents a node and each dislike pair represents an edge. The goal is to determine if the graph can be bipartite, which means we can color the graph using two colors such that no two adjacent nodes share the same color.
Step by Step Approach:
Below is the implementation of the above approach:
true
Time Complexity: O(n+m), where n is the number of people (nodes) and m is the number of dislike pairs (edges). This is because we traverse each node and edge once.
Auxiliary Space: O(n+m), due to the storage used for the adjacency list and the color array.