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?- A. True True False
- B. False True False
- C. False True True
- 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
- Problem: A 3-wheel lock starts at "000"; each move turns one wheel by ±1 (9 wraps to 0). Some codes are dead (the lock jams). Find the…
- Problem: Shortest paths from node 1 in a weighted DAG (negative edges allowed): topologically sort with Kahn's algorithm, then relax edges…
- Problem: An investor starts with capital w and may finish at most k projects; project i needs capital[i] to start and adds profits[i] when…
- Problem: A single CPU receives tasks (enqueue time, duration). When idle it starts the available task with the shortest duration (ties…
- Problem: Walk along buildings of given heights; climbing up by d needs d bricks or one ladder (going down is free). Return the furthest…
- Problem: Find the smallest range [lo, hi] that contains at least one number from each of k sorted lists (min-heap of one pointer per list…