Problem 886

Abstract / Summary

Determine if a group of people can be split into two groups so that no two people who dislike each other are in the same group.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0886.py

class Solution:
    def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
        pairs = defaultdict(list)
        for a, b in dislikes:
            pairs[a].append(b)
            pairs[b].append(a)

        one = 0
        two = 1
        unknown = None
        # no group yet
        group = { i: unknown for i in range(1, n + 1) }

        for i in range(1, n + 1):
            # already assigned, skip it
            if group[i] != unknown:
                continue

            # assign to first group by default
            group[i] = one
            # track their dislikes
            todo = [ i ]
            while todo:
                current  = todo.pop()
                opposite = group[current] ^ 1 # one => two, two => one
                for next in pairs[current]:
                    if group[next] == group[current]:
                        return False # collision, two disliking persons are in the same group

                    # assign other group (if not done yet)
                    if group[next] == unknown:
                        group[next] = opposite
                        todo.append(next)

        return True
35 lines | 1203 bytes | submitted January 6, 2024 | GitHub   28% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 51% (400k+ submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Depth First Search
  • Graph
  • Union Find
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The possibleBipartition method determines whether a set of n people can be divided into two groups such that no pair of people who dislike each other end up in the same group. The algorithm treats the dislike relationships as an undirected graph and attempts to color the graph using two colors. If a valid two-coloring exists, the function returns True; otherwise it returns False.

Key Steps

Building the adjacency list

pairs = defaultdict(list)
for a, b in dislikes:
    pairs[a].append(b)
    pairs[b].append(a)

All dislike pairs are stored in a dictionary where each key maps to a list of its neighbors. Using defaultdict(list) eliminates the need for explicit existence checks when appending neighbors.

Initializing the group mapping

one = 0
two = 1
unknown = None
group = { i: unknown for i in range(1, n + 1) }

Three symbolic constants represent the two possible groups (one and two) and the unassigned state (unknown). The group dictionary records the current assignment for every person, initially set to unknown.

Traversing each connected component

for i in range(1, n + 1):
    if group[i] != unknown:
        continue
    group[i] = one
    todo = [ i ]
    while todo:
        current = todo.pop()
        opposite = group[current] ^ 1
        for next in pairs[current]:
            if group[next] == group[current]:
                return False
            if group[next] == unknown:
                group[next] = opposite
                todo.append(next)

The outer loop iterates over all people, launching a new traversal whenever an unassigned person is encountered. The inner while loop implements an explicit stack (todo) to perform depth-first search without recursion. Each visited node’s neighbors are examined; unassigned neighbors receive the opposite group and are pushed onto the stack.

Detecting a conflict

if group[next] == group[current]:
    return False

If a neighbor already belongs to the same group as the current node, a conflict is detected and the function aborts early, returning False.

Edge Cases Handled

The algorithm gracefully handles isolated individuals because they appear in the group dictionary but have no entries in pairs; the DFS simply assigns them to the default group and moves on. Disconnected subgraphs are each processed independently by the outer loop, ensuring that a valid bipartition in one component does not interfere with another. The use of unknown as a sentinel value guarantees that previously assigned nodes are never re-initialized, preserving consistency across multiple components. When the dislikes list is empty, the adjacency structure remains empty, the loop assigns every person to the first group, and the function returns True without unnecessary work.

Performance Optimizations

The choice of defaultdict(list) provides O(1) amortized insertion for building the adjacency list, avoiding conditional checks for key existence. Representing groups with integer constants (0 and 1) enables the use of the bitwise XOR operator (^ 1) to flip between groups in constant time, eliminating branching logic. The iterative depth-first search using an explicit stack (todo) prevents the overhead and recursion depth limits associated with a recursive approach. Early termination on conflict detection prevents needless traversal of the remaining graph once a violation is found, saving cycles in dense or highly constrained inputs. Finally, the dictionary comprehension that initializes group runs in linear time with respect to n, establishing a compact lookup structure for constant-time group queries throughout the algorithm.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big group of friends who want to play a game, but some of them have had a disagreement and do not want to be on the same team. You have a list of people who dislike each other, and the goal is to see if you can split them into two separate teams so that no two people who dislike each other end up on the same side.

First, you look at the list of dislikes and draw lines to connect the people who cannot be together. This makes a map of all the arguments.

Next, you go through every person one by one. If a person does not have a team yet, you start by putting them on the first team. Then, you look at everyone they dislike and make sure those people go to the other team. You keep track of these new additions, and then you look at who those people dislike, and you keep switching groups back and forth like a mirror.

If you ever find that a person is already on a team but their friend who they dislike is also already on that same team, then you know it is impossible to separate them properly. You keep doing this until everyone is assigned to a team, and as long as no one is forced to play with someone they dislike, the plan works perfectly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.59 | σ = 0.78

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
34 links | 20 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   January 6, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality