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?- A. 6.0 3.0 -1.0 1.0
- B. 6.0 0.3333333333333333 -1.0 1.0
- C. 6.0 0.3333333333333333 -1.0 -1.0
- 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
- Problem: Reverse a word after prepending a marker using Java's StringBuilder. java StringBuilder sb = new StringBuilder("interview")…
- Problem: Find the longest substring in which every character appears at least k times (divide and conquer on characters that are too…
- Problem: Return the minimum number of characters to insert to make a string a palindrome. python def mininsert(s): t = s[::-1]; n = len(s)…
- Problem: Count the number of islands after each 'add land' operation on an initially all-water grid. python def islandsonline(R, C, ops)…
- Problem: Return the length of the shortest path that visits every node of a small undirected graph (start and end anywhere, edges…
- Problem: Count the number of ways to assign n distinct tasks to n workers where task i cannot go to worker i (derangements), modulo 10⁹ +…