LeetCode #990 Medium

Satisfiability of Equality Equations

Satisfiability of Equality Equations is LeetCode 990 (Medium). Each string in equations has four characters and reads either x==y or x!=y, where x and y are lowercase letters standing for integer variables.

  • Return true if you can give every letter an integer so that all the equations hold at once.
  • Return false if no such assignment exists.

There are only 26 possible variables and at most 500 equations.

Constraints
  • 1 <= equations.length <= 500
  • equations[i].length == 4
  • equations[i][0] is a lowercase letter.
  • equations[i][1] is either '=' or '!'.
  • equations[i][2] is '='.
  • equations[i][3] is a lowercase letter.
graphsunion-find
Open on LeetCode ↗
02

Intuition

Equality spreads along chains: if a==b and b==c, then a must equal c even though no equation says so. So first join the two letters of every == into one group; all letters in a group are forced to share a value. After that, a != can only fail if both of its letters ended up in the same group.

  • Why that is enough: give each group its own number. Every == holds because its letters share a group, and every != between two different groups holds because their numbers differ.
  • Union find: stores the groups, merges two of them in about O(1), and tells you which group a letter belongs to in about O(1).
How to spot this pattern

Rules of the form "these must be equal" spread through chains, while "these must differ" only breaks inside a chain. Grouping by the equal rules and then checking the different ones is a union-find job.

03

Approach

Try it first

Before reading on, decide what a==b and b==c force about a and c, and why the != equations cannot be checked the moment they are read. Aim for two passes over the list.

1

Give each letter its own group

Make parent = [0, 1, ..., 25], one slot per lowercase letter, so every letter starts as the root of a group of one. find(x) follows parent links up to the root, pointing each node at its grandparent on the way so later lookups are shorter.

2

Pass 1: join the letters of every ==

For each equation whose second character is =, find the roots of both letters and point one root at the other. Letters that are only linked through others, like a and c through b, end up under the same root.

3

Pass 2: test every !=

For each equation whose second character is !, find both roots. The same root means the equalities force the two letters to be equal, so this != can never hold: return false. If every != sees two different roots, return true.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def equationsPossible(self, equations: List[str]) -> bool:
▶3 parent = list(range(26))
▶4 
▶5 def find(x):
▶6 while parent[x] != x:
▶7 parent[x] = parent[parent[x]]
▶8 x = parent[x]
▶9 return x
▶10 
▶11 for eq in equations:
▶12 if eq[1] == "=":
▶13 a, b = ord(eq[0]) - ord("a"), ord(eq[3]) - ord("a")
▶14 parent[find(a)] = find(b)
▶15 for eq in equations:
▶16 if eq[1] == "!":
▶17 a, b = ord(eq[0]) - ord("a"), ord(eq[3]) - ord("a")
▶18 if find(a) == find(b):
▶19 return False
▶20 return True
equationsgroupsa=bb≠arootarootbevery letter starts in its own group
lettersa, b
Each letter used in the equations starts as a group of one and is its own root. A group will collect letters that are forced to be equal; nothing is forced yet.
pass 1: join equalgroupsa=bjoinedb≠aarootba equals b → join their groups
root of aa
root of bb
a must equal b, so their groups merge: a's root a now points to b, which becomes the root of the joined group. Every letter in it must take the same value.
pass 1: join equalgroupsa=bjoinedb≠alaterarootbb ≠ a waits for pass 2
equationb ≠ a
An inequality cannot be judged yet: an equality further down the list could still put b and a in one group. Skip it in this pass.
pass 2: check unequalgroupsa=bskipb≠alaterarootba equals b was used in pass 1
equationa = b
Equalities have already done their job by building the groups, so pass 2 skips them.
pass 2: check unequalgroupsa=bskipb≠aclasharootbb and a share a group → false
root of bb
root of ab
resultfalse
b and a both lead to the root b, so the equalities force them to be equal. b ≠ a can never hold, and no assignment satisfies every equation: return false.
05

Common pitfalls

Checking != in the same pass as ==

✗ Wrong
for eq in equations:
    if eq[1] == "=":
        union(a, b)
    elif find(a) == find(b):
        return False
✓ Right
for eq in equations:
    if eq[1] == "=":
        union(a, b)
for eq in equations:
    if eq[1] == "!" and find(a) == find(b):
        return False

["a!=c","a==b","b==c"] checks a!=c while a and c are still in separate groups, so it passes. The two equalities that join them come later, and the function returns true for a list that has no solution.

Linking the letters instead of their roots

✗ Wrong
parent[a] = b
✓ Right
parent[find(a)] = find(b)

["a==b","a==c","b!=c"] sets parent[a] = b, then overwrites it with parent[a] = c. Now b is cut off from a and c, the check b!=c sees two roots, and the answer comes back true instead of false.

06

Edge cases

A letter unequal to itself, ["a!=a"]

Both sides have the same root, so pass 2 returns false. That is right: no integer differs from itself.

Only != equations, e.g. ["a!=b","b!=c"]

Nothing is joined, every check sees two roots, and the answer is true. Inequality does not chain: a = 1, b = 2, c = 1 satisfies both, even though a equals c.

07

Complexity

Time
O(n)
Space
O(1)
n is the number of equations. Each pass calls find twice per equation, and with only 26 letters and path halving each call is a few steps. The parent array always has 26 slots, whatever n is.
08

Satisfiability of Equality Equations FAQ

Can it be solved with DFS?

Yes. Build a graph with an edge for every ==, label each connected component with DFS or BFS, then check that no != joins two letters with the same label. It is the same two-pass idea with components in place of union-find groups, and it costs the same on 26 letters.