sagelearnai

Satisfiability of Equality Equations

Difficulty: Medium · Pattern: Union-Find · LeetCode #990

Each equation is a 4-character string, either "a==b" or "a!=b", over single lowercase-letter variables. Return true if some assignment of integers to the variables satisfies all the equations.

Examples

text
["a==b","b!=a"]          →  false
["b==a","a==b"]          →  true
["a==b","b==c","a==c"]   →  true
["a==b","b!=c","c==a"]   →  false

Hints

  1. Equality is transitive, so all variables linked by == must share one value: those are components.
  2. Process all the == first, then check each !=.

Approach

  1. Union-Find over 26 letters. For every x==y, union(x, y).
  2. For every x!=y, if find(x) == find(y), return false.

The two-pass order is essential. If you check a != before all the == have been processed, a later equality could merge the pair after you already said yes. "a!=a" correctly returns false. O(n · α(26)).

Complexity

Time: O(n). Space: O(1) (26 letters).

Python solution
def equationsPossible(equations):
    parent = list(range(26))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    for e in equations:
        if e[1] == '=':
            parent[find(ord(e[0]) - 97)] = find(ord(e[3]) - 97)
    for e in equations:
        if e[1] == '!' and find(ord(e[0]) - 97) == find(ord(e[3]) - 97):
            return False
    return True
JavaScript solution
function equationsPossible(equations) {
  const parent = [...Array(26).keys()];
  const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };
  const id = (ch) => ch.charCodeAt(0) - 97;
  for (const e of equations) if (e[1] === '=') parent[find(id(e[0]))] = find(id(e[3]));
  for (const e of equations) if (e[1] === '!' && find(id(e[0])) === find(id(e[3]))) return false;
  return true;
}