Satisfiability of Equality Equations — LeetCode 990 Python Solution

MediumUnion FindGraphArrayString
Problem
#990
Pattern
Union-Find
Reading time
3 min

The problem

You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names. Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise.

Example

Input
equations = ["a==b","b!=a"]
Output
false
Explanation
If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.

Python solution

Python
class Solution:
    def equationsPossible(self, equations: List[str]) -> bool:
        def find(x):
            if p[x] != x:
                p[x] = find(p[x])
            return p[x]

        p = list(range(26))
        for e in equations:
            a, b = ord(e[0]) - ord('a'), ord(e[-1]) - ord('a')
            if e[1] == '=':
                p[find(a)] = find(b)
        for e in equations:
            a, b = ord(e[0]) - ord('a'), ord(e[-1]) - ord('a')
            if e[1] == '!' and find(a) == find(b):
                return False
        return True

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 990. Satisfiability of Equality Equations is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 990. Satisfiability of Equality Equations?
LeetCode 990. Satisfiability of Equality Equations is rated Medium on LeetCode.
What is the time complexity of LeetCode 990. Satisfiability of Equality Equations?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 990. Satisfiability of Equality Equations?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 990. Satisfiability of Equality Equations cover?
LeetCode 990. Satisfiability of Equality Equations is tagged Union Find, Graph, Array and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview