Python 0990.py
class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
# union-find, copied from problem 721
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(x, y):
x = find(x)
y = find(y)
if x == y:
return
if x < y:
parent[y] = x
else:
parent[x] = y
# find all variables in use
parent = {}
for e in equations:
left = e[0]
right = e[3]
parent[left ] = left
parent[right] = right
# identical variables
for e in equations:
compare = e[1:3]
if compare == "==":
left = e[0]
right = e[3]
union(left, right)
# negated variables must not have the same parent
for e in equations:
compare = e[1:3]
if compare == "!=":
left = e[0]
right = e[3]
if find(left) == find(right):
return False
return True
Difficulty
and has an acceptance rate of about 52% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Graph Theory
- String
- Union Find
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation determines whether a list of equality and inequality constraints between single-character variables can be satisfied simultaneously. It employs a union-find (disjoint-set) data structure to group variables that must be equal and then checks that no inequality contradicts those groupings. The algorithm proceeds in three logical phases: initialization of the disjoint-set, merging of equal variables, and validation of inequalities.
Initialization of the Disjoint-Set
A dictionary named parent stores the representative element for each variable. The code iterates over every equation, extracts the left-hand and right-hand variable characters, and inserts them into the dictionary with themselves as initial parents. This guarantees that every variable appearing in the input has an entry, even if it only participates in an inequality.
parent = {}
for e in equations:
left = e[0]
right = e[3]
parent[left ] = left
parent[right] = right
Core Union-Find Operations
Two nested helper functions implement the essential union-find operations.
Find with Path Compression
The find function follows parent links until it reaches the root of the set. While unwinding the recursion, it assigns each visited node directly to the root, thereby flattening the tree structure for future queries.
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
Union with Deterministic Root Selection
The union function first locates the roots of the two variables. If the roots differ, it attaches the larger root to the smaller one, using the lexical order of the variable characters as a simple heuristic. This deterministic choice reduces the height of the trees without requiring an explicit rank array.
def union(x, y):
x = find(x)
y = find(y)
if x == y:
return
if x < y:
parent[y] = x
else:
parent[x] = y
Merging Variables Declared Equal
The second pass over the input processes equations whose operator is "==". For each such equation, the two involved variables are united, causing their sets to share a common representative. This step builds the equivalence classes implied by the equalities.
for e in equations:
compare = e[1:3]
if compare == "==":
left = e[0]
right = e[3]
union(left, right)
Validating Inequality Constraints
The final pass examines equations with the "!=" operator. For each inequality, the algorithm retrieves the representatives of the two variables. If the representatives are identical, the inequality contradicts a previously established equality, and the function returns False immediately. If no contradiction is found, the function concludes that the constraints are satisfiable and returns True.
for e in equations:
compare = e[1:3]
if compare == "!=":
left = e[0]
right = e[3]
if find(left) == find(right):
return False
return True
Edge Cases Handled
The code gracefully handles several subtle situations:
- Self-Equality - When an equation like
"a==a"appears, the union operation detects that both variables already share the same root and performs no change, preserving correctness. - Self-Inequality - An equation such as
"a!=a"triggers the inequality check; thefindcall returns the same root for both sides, causing an immediateFalsereturn, which correctly reflects the impossibility of the constraint. - Variables Appearing Only in Inequalities - Because the initialization step adds every variable to the
parentdictionary regardless of the operator, variables that appear solely in"!="equations are still part of the disjoint-set structure, allowing the laterfindcalls to succeed without a KeyError. - Redundant Constraints - Multiple identical equalities or inequalities are processed without adverse effect; the union operation becomes a no-op when the variables are already connected, and the inequality check simply repeats the same verification.
Performance Optimizations
The implementation incorporates two classic optimizations for disjoint-set structures:
- Path Compression in the
findfunction reduces the depth of the tree after each lookup, ensuring that subsequentfindoperations on the same element execute in near-constant time. - Deterministic Root Selection based on lexical ordering provides a lightweight form of union by rank. By consistently attaching the larger identifier to the smaller one, the tree height is limited without the overhead of maintaining explicit rank information.
Additionally, the algorithm performs an early exit as soon as a contradictory inequality is detected, avoiding unnecessary processing of the remaining equations. This short-circuit behavior can dramatically reduce runtime on inputs where a conflict appears early in the list.
Overall, the code presents a clear, methodical application of union-find to resolve equality and inequality constraints, with thoughtful handling of edge conditions and built-in optimizations that keep the execution efficient for typical problem sizes.
ELI5 - Simplified Explanation
Imagine there are groups of children playing with blocks. Each child has a letter on their shirt, and because they are playing together, some children are best friends and others do not want to be near each other.
First, the code gives every child a little box to hold their own name, so they know who they are. Then, it looks at the notes written down about which children are best friends. When it sees a note saying two children are equal, it puts those two children into the same group. Think of this like tying their shoelaces together so they have to stay in the same party group.
After that, the code looks at the notes that say two children cannot be in the same group. It checks to see if those two children were already tied together as friends. If it finds that two children who are supposed to be separated are actually in the same group, it knows something went wrong. If everyone who is supposed to be apart is kept in different groups, then the playdate works out perfectly.
Code Quality
Complexity Analysis
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
Other Solutions
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 | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | begeekmyfriend | C | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| FelixFan1122 | Java | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| begeekmyfriend | C | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| FelixFan1122 | Java | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1019: Next Greater Node In Linked List
- problem 675: Cut Off Trees for Golf Event
- problem 839: Similar String Groups
- problem 864: Shortest Path to Get All Keys
Extra
- 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