Satisfiability of Equality Equations
Decide whether letter equations can all hold, by merging every == pair first and then checking each != pair.
The problem
You get a list equations of four-character strings such as "a==b" or "a!=b", where each lowercase letter is a variable that holds an integer. Return true if you can give the variables values so that every equation holds, and false otherwise.
Input equations = ["x==y", "y==z", "x!=z"]
Output false
x == y and y == z force x == z, which breaks x != z.
Input equations = ["p==q", "r!=s", "q!=r"]
Output true
Give p and q one value, r a second value and s a third.
Key constraint: There are only 26 possible variables, one per lowercase letter, so the union-find has 26 entries.
How to spot the pattern
- Equalities chain together: a == b and b == c mean a == c.
- You need to know which variables are forced into the same group, then look for a conflict.
The idea
Equal variables form groups that must share one value, and different groups can always get different values. So first merge the two letters of every == equation with union-find. After that, a != equation fails exactly when its two letters ended up in the same group, and if none fails, giving each group its own value satisfies everything.
Brute force: Try every way of giving values to the letters and test all the equations each time, which grows exponentially with the number of letters.
Step by step
- 1Make a union-find over the 26 letters.
- 2For every equation with
==, merge the groups of its two letters. - 3For every equation with
!=, find the roots of its two letters. - 4If any
!=equation has both letters in the same group, returnfalse; otherwise returntrue.
See the pattern move
The union-find pattern on a small example. Step through it, or press play.
Code
class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
parent = list(range(26)) # one group per letter
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving: point to the grandparent
x = parent[x]
return x
for eq in equations:
if eq[1] == "=": # "a==b": both letters must hold the same value
parent[find(ord(eq[0]) - ord("a"))] = find(ord(eq[3]) - ord("a"))
for eq in equations:
if eq[1] == "!" and find(ord(eq[0]) - ord("a")) == find(ord(eq[3]) - ord("a")):
return False # "a!=b", but a and b were forced into one group
return TrueComplexity
Time
O(n)
Space
O(1)
n is the number of equations: two passes over them, and with only 26 letters each find takes a few steps at most; the parent array always has 26 entries.
Watch out for
- Handling the equations in input order: a
!=early in the list can be broken by==equations that come later, so merge all the==first. - Missing
"a!=a", which can never hold. - Reading the wrong characters: the letters are at index 0 and index 3, and index 1 tells you whether it is
==or!=.
Follow-up questions
What if the variables were whole words instead of single letters?
Give each word an index with a hash map the first time you see it, then run the same union-find on those indices.
What if the equations had ratios, like a / b = 2?
Store with each parent link the ratio to the parent, so finding the root also gives a variable's ratio to its root. That is Evaluate Division.
In Hinglish
Pehle saare == waale letters ko ek group mein jodo, phir har != check karo. Kisi != ke dono letter ek hi group mein nikle toh false.