TRT
Sign in
mediumAdvancedLeetCode#union-find#two passes

Satisfiability of equality equations

Decide whether a set of equalities and inequalities between variables can all hold, by unioning the equalities first.

The Runtime Theory Team1 min read
Taught inUnion by rank and path compressionPro — members onlyAttaching the smaller tree under the larger keeps trees logarithmically shallow, and pointing every visited node straight at the root flattens them further. Together they make union-find's operations nearly constant time.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inequations = ["a==b", "b!=a"]

outfalse

inequations = ["b==a", "a==b"]

outtrue

inequations = ["a==b", "b!=c", "c==a"]

outfalse

inequations = ["c==c", "b==d", "x!=z"]

outtrue

inequations = ["a!=a"]

outfalse

Each equation has the form "x==y" or "x!=y", where x and y are lowercase letters. Return true if it is possible to assign integers to the variables so that every equation holds.

Before you code

Equalities are transitive, so they build groups. Why must all the equalities be processed before any inequality is checked?

Hints

  1. Use a union-find over the 26 letters.
  2. First pass: union the two sides of every "==" equation.
  3. Second pass: for every "!=" equation, if both sides have the same root, return false. Note that "a!=a" always fails.

Production & complexity notes

When solving Satisfiability of equality equations on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Union by rank and path compression to reinforce the underlying pattern.

What it practices

Equivalence classes with union-find, from Union by rank and path compression.

Not started

Sign in to save your learning progress.

Sign in to save