SDE & MLE Prep

990. Satisfiability of Equality Equations

Problem

Each equation is a 4-character string "x==y" or "x!=y" over single lowercase-letter variables. Decide whether integers can be assigned to the variables so that every equation holds.

Example: ["a==b","b!=a"] → false; ["b==a","a==b"] → true

First union all a==b; then every a!=b must have different roots.

Complexity: O(n · α(26)).

class Solution:
    def equationsPossible(self, equations: List[str]) -> bool:
        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)
        return all(find(ord(e[0]) - 97) != find(ord(e[3]) - 97) for e in equations if e[1] == "!")