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

Problem: Evaluate division queries on the ratio graph a/b = 2, b/c = 3, d/e = 4.

Problem: Evaluate division queries on the ratio graph a/b = 2, b/c = 3, d/e = 4.
from collections import defaultdict
g = defaultdict(dict)
for (a, b), k in [(("a", "b"), 2.0), (("b", "c"), 3.0), (("d", "e"), 4.0)]:
    g[a][b] = k; g[b][a] = 1 / k
def ask(x, y, seen=None):
    if x not in g or y not in g: return -1.0
    if x == y: return 1.0
    seen = seen or {x}
    for nb, w in g[x].items():
        if nb not in seen:
            seen.add(nb); r = ask(nb, y, seen)
            if r != -1.0: return w * r
    return -1.0
print(ask("a", "c"), ask("c", "b"), ask("a", "e"), ask("x", "x"))
What is printed?
  1. A. 6.0 3.0 -1.0 1.0
  2. B. 6.0 0.3333333333333333 -1.0 1.0
  3. C. 6.0 0.3333333333333333 -1.0 -1.0
  4. D. 5.0 0.3333333333333333 -1.0 -1.0

Correct answer: C. 6.0 0.3333333333333333 -1.0 -1.0

a/c = (a/b)(b/c) = 6; c/b uses the reverse edge 1/3. a and e are in different components → −1. An unknown variable x has no information even for x/x, so −1 (checked before the x == y shortcut). O(V + E) per query.

More Coding Interview Problems questions

Exams that ask this topic