Satisfiability of Equality Equations - 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.

Input & Output

Example 1 — Basic Valid Case
$ Input: equations = ["a==b","b!=c"]
Output: true
💡 Note: Variables a and b must be equal, and b must not equal c. We can assign a=b=0 and c=1, satisfying both equations.
Example 2 — Contradiction
$ Input: equations = ["a==b","b==c","a!=c"]
Output: false
💡 Note: If a==b and b==c, then a==c by transitivity. But we also have a!=c, which creates a contradiction.
Example 3 — Self Reference
$ Input: equations = ["a!=a"]
Output: false
💡 Note: A variable cannot be not equal to itself, so this equation is impossible to satisfy.

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

Visualization

Tap to expand
Satisfiability of Equality Equations INPUT equations array: "a==b" "b!=c" Variables: a b c == != Green = equality Red dashed = inequality ["a==b","b!=c"] ALGORITHM STEPS (Union-Find Approach) 1 Initialize Union-Find Each variable is its own parent a:a b:b c:c 2 Process "==" equations Union(a, b) - merge sets a,b:a c:c 3 Process "!=" equations Check b != c Find(b)=a, Find(c)=c a != c (OK - different) 4 Validate all constraints No conflicts found All equations satisfied! FINAL RESULT Final Union-Find State: a b c a and b in same set c in different set Verification: a==b: same set [OK] b!=c: different sets [OK] Possible assignment: a=1, b=1, c=2 true Key Insight: Use Union-Find to group variables connected by "==" equations. Then verify that no "!=" equation connects variables in the same group. If any inequality constraint connects same-group variables, return false. Time: O(n * alpha(n)) where alpha is inverse Ackermann function (nearly constant). TutorialsPoint - Satisfiability of Equality Equations | Union-Find Optimal Approach
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen