Satisfiability of Equality Equations (LeetCode 990): Solution and Explanation
Decide whether a list of one-letter equations like a==b and b!=c can all be true at once.
Intuition
Equality is transitive. If a==b and b==c, then a and c are forced to be equal even though no equation names them together. So the == equations split the letters into groups, and each group must share one value.
Inequalities never force anything. If every != pair lies in two different groups, give each group its own number and every equation holds. The only way to fail is a != between two letters of the same group, including a letter compared with itself.
Union-find is built for exactly this: merge groups as == equations arrive, and later ask whether two letters ended up with the same root.
Order matters. A != that looks harmless when first read can become a contradiction after a later ==, so do all merges first and all checks second.
Approach: Union-find in two passes
- Create
parentof size 26 withparent[x] = x. - Pass 1: for each equation whose middle is
==, setparent[find(x)] = find(y)to merge the two groups. - Pass 2: for each equation whose middle is
!=, computefind(x)andfind(y). - If they are equal, the equalities force x and y together, so return
false. - If every check passes, return
true.
Step-by-step example
equations = ["a==b","b!=a"]
- Every letter starts as its own root.
- Pass 1, "a==b": the roots are a and b, so point parent[a] at b. Now a and b share root b.
- Pass 2, "b!=a": find(b) = b and find(a) = b. Same root, so the inequality is impossible.
- Return false.
Code: Python, Java, C++
1class Solution:
2 def equationsPossible(self, equations: List[str]) -> bool:
3 parent = list(range(26))
4
5 def find(x):
6 while parent[x] != x:
7 parent[x] = parent[parent[x]]
8 x = parent[x]
9 return x
10
11 for eq in equations:
12 if eq[1] == '=':
13 parent[find(ord(eq[0]) - 97)] = find(ord(eq[3]) - 97)
14 for eq in equations:
15 if eq[1] == '!' and find(ord(eq[0]) - 97) == find(ord(eq[3]) - 97):
16 return False
17 return True1class Solution {
2 private int[] parent = new int[26];
3
4 private int find(int x) {
5 while (parent[x] != x) {
6 parent[x] = parent[parent[x]];
7 x = parent[x];
8 }
9 return x;
10 }
11
12 public boolean equationsPossible(String[] equations) {
13 for (int i = 0; i < 26; i++) parent[i] = i;
14 for (String eq : equations) {
15 if (eq.charAt(1) == '=') parent[find(eq.charAt(0) - 'a')] = find(eq.charAt(3) - 'a');
16 }
17 for (String eq : equations) {
18 if (eq.charAt(1) == '!' && find(eq.charAt(0) - 'a') == find(eq.charAt(3) - 'a')) return false;
19 }
20 return true;
21 }
22}1class Solution {
2 int parent[26];
3
4 int find(int x) {
5 while (parent[x] != x) {
6 parent[x] = parent[parent[x]];
7 x = parent[x];
8 }
9 return x;
10 }
11
12public:
13 bool equationsPossible(vector<string>& equations) {
14 for (int i = 0; i < 26; i++) parent[i] = i;
15 for (const string& eq : equations) {
16 if (eq[1] == '=') parent[find(eq[0] - 'a')] = find(eq[3] - 'a');
17 }
18 for (const string& eq : equations) {
19 if (eq[1] == '!' && find(eq[0] - 'a') == find(eq[3] - 'a')) return false;
20 }
21 return true;
22 }
23};Time and space complexity
O(n)
Each equation does a constant number of find operations, and with only 26 letters and path compression every find is effectively constant time.
O(1)
The parent array always has 26 entries, regardless of how many equations there are.
Other approaches
Graph coloring with DFS (time O(n), space O(1))
Build an undirected graph from the == edges, label each connected component with DFS, then check that every != pair has different labels. Same idea as union-find, slightly more code.
Single pass in input order (time O(n), space O(1))
Checking each != as soon as it appears is wrong: ["a!=c", "a==b", "b==c"] would pass the early check even though the later equalities make a equal to c.
Common mistakes
- Checking != equations in the same pass as the merges. Later equalities can join letters that an earlier inequality separated.
- Forgetting that "a!=a" is always false. The two-pass union-find handles it for free because find(a) equals find(a).
- Reading the wrong characters. The letters are at index 0 and index 3, and the operator is decided by index 1.
- Merging letters instead of roots, as in parent[x] = y. That can break an existing group apart; always link find(x) to find(y).
Frequently asked questions
Why do inequalities not need to be merged or tracked?
An inequality only rules something out. As long as its two letters are in different groups, you can give those groups different numbers, and there are infinitely many integers to choose from, so all inequalities can be satisfied together.
Why is union-find better than checking pairs directly?
Equality chains can be long, so whether two letters must be equal depends on many equations at once. Union-find answers that in near constant time per query after the merges.
Do I need union by rank here?
Not really. There are only 26 letters, so trees stay tiny. Path compression alone, or even no optimization, is fast enough.
What is the time complexity?
O(n) time for n equations and O(1) extra space, since the parent array has a fixed size of 26.