Satisfiability of Equality Equations solution explained

Satisfiability of Equality Equations gives you statements like "a==b" and "a!=c" over single lowercase letters and asks whether some assignment of numbers makes all of them true at once. Put letters joined by "==" into the same group with union-find, then check that no "!=" statement has both letters in one group. Doing all equalities before any inequality is the key, and the whole check runs in O(n) for n statements, since there are only 26 letters.

By Published 7 min read

The problem in plain words

Each statement is a string of four characters: a lowercase letter, then either == or !=, then another lowercase letter. Letters stand for integer variables. Return true if you can give each letter a number so that every statement in the list holds, and false otherwise. The order of statements in the list has no meaning; they all have to hold together.

Statement lists written for this page
StatementsAnswerWhy
"p==q", "q==r", "p!=r"falsep, q and r must all be equal, so p cannot differ from r
"m!=n", "n==o", "o!=m"trueGive n and o the value 1 and m the value 0
"c!=d", "d==e", "e==c"falseThe inequality comes first, but the two later equalities still force c, d and e together
"x==y", "u==v", "x!=u"trueTwo separate groups, {x, y} and {u, v}, can hold different values
"z!=z"falseNo number differs from itself
"a==a"trueAlways true, and it adds nothing
Statement lists written for this page. Scroll sideways on a small screen.

What the interviewer is checking

This is often the first union-find question in a loop, so the interviewer checks whether you see that equality is transitive and therefore groups letters, while inequality does not chain at all (a!=b and b!=c says nothing about a and c). The common trap is processing the list in order and checking each inequality as you meet it, which misses equalities that appear later. Spotting the two-pass structure, and saying why it is needed, is most of the credit.

Brute force: try every assignment

If k different letters appear, any satisfying assignment can be squeezed into the values 0 to k - 1, since only equal versus different matters. So try all k to the power k ways to give each letter one of those values and test every statement. This is exponential and only useful as a checker for a handful of letters.

from itertools import product

def can_satisfy_slow(statements):
    letters = sorted({s[0] for s in statements} | {s[3] for s in statements})
    k = len(letters)
    for values in product(range(k), repeat=k):
        value = dict(zip(letters, values))
        if all((value[s[0]] == value[s[3]]) == (s[1] == "=")
               for s in statements):
            return True
    return False
Python: try every assignment of values 0..k-1. Exponential, for checking only.

The middle characters decide the kind of statement: the second character is = for == and ! for !=. The test compares "are the two values equal" with "is this an equality", which is true exactly when the statement holds.

Optimal: union-find over 26 letters

Give each letter a slot in a 26-entry parent array. First pass: for every equality, merge the groups of its two letters. Second pass: for every inequality, look up both letters' group leaders. If they match, the statement contradicts the equalities, so return false. If no inequality fails, a valid assignment exists: give each group its own number.

def can_satisfy(statements):
    parent = list(range(26))

    def find(i):
        if parent[i] != i:
            parent[i] = find(parent[i])   # depth is at most 26, recursion is safe
        return parent[i]

    for s in statements:
        if s[1] == "=":
            parent[find(ord(s[0]) - 97)] = find(ord(s[3]) - 97)

    for s in statements:
        if s[1] == "!" and find(ord(s[0]) - 97) == find(ord(s[3]) - 97):
            return False
    return True
Python: two passes, equalities merge and inequalities check

Recursion is fine here because no chain can be longer than 26 letters. There is no need for union by rank either: with 26 elements, the tree depth is bounded no matter how you merge. A statement like "z!=z" fails naturally, because find(z) equals find(z).

function canSatisfy(statements) {
  const code = (ch) => ch.charCodeAt(0) - 97;
  const adj = Array.from({ length: 26 }, () => []);
  for (const s of statements) {
    if (s[1] === "=") {
      adj[code(s[0])].push(code(s[3]));
      adj[code(s[3])].push(code(s[0]));
    }
  }
  const group = new Array(26).fill(-1);
  for (let start = 0; start < 26; start++) {
    if (group[start] !== -1) continue;
    group[start] = start;
    const stack = [start];
    while (stack.length > 0) {
      for (const next of adj[stack.pop()]) {
        if (group[next] === -1) {
          group[next] = start;
          stack.push(next);
        }
      }
    }
  }
  return statements.every((s) => s[1] === "=" || group[code(s[0])] !== group[code(s[3])]);
}
JavaScript: label components with a DFS over an equality graph, then check

The JavaScript version shows the same idea without union-find: build an undirected graph from the equalities, label each connected component, and compare labels. Both are linear in the number of statements. Union-find is the more common answer because it extends easily if statements arrive one at a time.

Complexity

n statements, k distinct letters (k at most 26)
ApproachTimeExtra space
Every assignment of valuesO(k^k × n)O(k)
Union-find, two passesO(n α(26)), effectively O(n)O(1), 26 slots
Equality graph plus component labelsO(n + 26)O(n) for the adjacency lists
n statements, k distinct letters (k at most 26). Scroll sideways on a small screen.

Edge cases

  • "z!=z": impossible on its own, so false.
  • "a==a": always true. Merging a letter with itself changes nothing.
  • An inequality listed before the equalities that contradict it: only a two-pass solution catches it.
  • Only inequalities between different letters: always true, since every letter can have its own value.
  • A long chain a==b, b==c, up to y==z, plus a!=z: false, and the recursion depth stays within 26.
  • The same statement repeated: harmless in both passes.

Common mistakes

  • Checking each inequality as soon as it appears in the list, before later equalities have been merged.
  • Treating inequality as transitive and concluding that a!=b and b!=c forces a==c, or the opposite.
  • Reading the wrong characters: the letters are at positions 0 and 3, and the operator is decided by position 1.
  • Merging letters directly (parent[a] = b) instead of merging their roots, which can split groups.
  • Assuming a statement with the same letter on both sides is always fine, and missing "x!=x".

Follow-up questions

  • Statements arrive one at a time; report the first one that makes the list impossible. Keep a list of the inequalities seen so far. A new inequality is checked against the current groups at once. A new equality merges two groups, and then every stored inequality is rechecked (or only those that touch the two merged groups, if you index them by group).
  • Variables are full names, not single letters. Map each name to an index with a hash map; the logic is unchanged and space becomes O(number of names).
  • Add less-than statements. Now order matters: you need groups for equality and a directed graph between groups for less-than, then a cycle check, which turns into a topological sort.
  • Return an actual assignment. Give each group leader a distinct number and copy it to its members.

How to explain it out loud

Fictional example

Why two passes
Candidate
Equality is transitive, so equal letters form groups. Inequality doesn't chain, it's only a constraint between two groups.
Candidate
First I go through all the equalities and merge their letters with union-find, 26 slots.
Interviewer
Why not handle the inequalities as you go?
Candidate
Because an equality later in the list could join two letters I already checked as different. So after merging everything, I check each inequality: if both letters share a root, it's impossible.
Candidate
That's linear in the number of statements and constant space.

Similar String Groups uses the same grouping idea, except the "equal" links must be discovered by comparing strings. Most Stones Removed with Same Row or Column merges stones through shared rows and columns. If ordering constraints are added, the problem turns into the kind of check in Sequence Reconstruction.

Practicing it with Natively

The one sentence worth rehearsing is why the equalities must all be merged first. When you practice on a Mac or Windows PC, Natively can read the statement list from a screenshot, suggest the two-pass union-find approach, and transcribe your explanation so you can check whether the ordering trap came up before you started coding. The LeetCode practice helper page shows that setup.

Questions people ask

How do you solve Satisfiability of Equality Equations?

Use union-find over the 26 letters. First merge the two letters of every equality, then check every inequality: if both letters have the same root, return false. Otherwise return true.

Why process equalities before inequalities?

The list order has no meaning. An equality that appears after an inequality can still force its two letters together, so all merges must happen before any check.

What is the time complexity?

O(n) for n statements, with constant space, since union-find runs over a fixed set of 26 letters.

Is a statement like x!=x possible?

No. A letter always shares a group with itself, so any inequality between a letter and itself makes the answer false.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP