Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Given equations like "a==b" and "b!=c" over single-letter variables, can all hold at once? Union all '==' pairs first, then check every '!=' pair.

Problem: Given equations like "a==b" and "b!=c" over single-letter variables, can all hold at once? Union all '==' pairs first, then check every '!=' pair.
def satisfiable(eqs):
    p = {}
    def find(x):
        p.setdefault(x, x)
        while p[x] != x: x = p[x]
        return x
    for e in eqs:
        if e[1] == "=": p[find(e[0])] = find(e[3])
    return all(find(e[0]) != find(e[3]) for e in eqs if e[1] == "!")
print(satisfiable(["a==b", "c==d", "b!=c", "d==a"]), satisfiable(["x==y", "y==z", "z!=w", "w!=x"]), satisfiable(["p!=p"]))
What is printed?
  1. A. True True False
  2. B. False True False
  3. C. False True True
  4. D. False False False

Correct answer: B. False True False

Equalities are transitive, so they define groups; an inequality fails iff both sides are in one group. First: a = b, c = d, d = a merge all four, so b != c fails – processing equations in input order (checking b != c before d == a is seen) would wrongly accept. Second: {x, y, z} and {w} → fine. "p!=p" is always false. O(n·α).

More Coding Interview Problems questions

Exams that ask this topic