Python coding

Unit conversions from known facts

Each fact [a, b, k] says that one a equals k units of b, where k is a positive number, not always whole. Write convert(facts, queries), which returns one answer per query, in order: for [x, y], how many y equal one x, chaining facts in either direction, or -1.0 if the facts don't determine it. A unit that appears in no fact is unknown, even in [x, x].

The facts never contradict each other. Aim for near-constant time per query, not a new search each time. The tests call the provided run_conversions(facts, queries), which rounds your answers to 6 decimals, so floating-point noise doesn't matter.

Besides the tests, one large input (2,000 units, 2,000 queries) with a ~300 ms limit (scaled to your device's speed): brute force won't pass.

  • run_conversions([["km","m",1000],["m","cm",100]], [["km","cm"],["cm","km"],["m","m"],["km","mile"]]) → [100000,0.00001,1,-1]
  • run_conversions([["hour","minute",60],["day","hour",24],["kg","g",1000]], [["day","minute"],["minute","hour"],["day","kg"],["g","kg"]]) → [1440,0.016667,-1,0.001]
  • run_conversions([["foot","inch",12]], [["inch","foot"],["yard","yard"],["foot","foot"]]) → [0.083333,-1,1]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Units joined by facts form groups, and inside a group every unit converts to every other. Union-find keeps the groups; the twist is a number on each link.

Hint 2

Store ratio[u]: how many parent[u] make one u. While find compresses a path, multiply the ratios up to the root, so one x is ratio[x] / ratio[y] units of y.

Hint 3

For a fact one a = k b with roots ra and rb, hang rb under ra with ratio[rb] = ratio[a] / (k * ratio[b]). Swap sides and use 1 / k to hang the smaller tree.

Solution and why it works
pythonO((F + Q)·α(n)), F facts, Q queries, n units · O(n)
# --- your code ---
def convert(facts: list[list], queries: list[list[str]]) -> list[float]:
    parent, size, ratio = {}, {}, {}             # ratio[u] = how many parent[u] make one u

    def find(u: str) -> str:
        if parent[u] != u:
            root = find(parent[u])               # first flatten the parent's path
            ratio[u] *= ratio[parent[u]]         # (u in parent) * (parent in root) = u in root
            parent[u] = root
        return parent[u]

    for a, b, k in facts:                        # one a = k b
        for unit in (a, b):
            if unit not in parent:
                parent[unit], size[unit], ratio[unit] = unit, 1, 1.0
        ra, rb = find(a), find(b)
        if ra == rb:
            continue                             # already linked: the fact adds nothing new
        if size[ra] < size[rb]:                  # hang the smaller tree under the larger root
            ra, rb, a, b, k = rb, ra, b, a, 1 / k
        parent[rb], ratio[rb] = ra, ratio[a] / (k * ratio[b])    # one rb = this many ra
        size[ra] += size[rb]
    linked = lambda x, y: x in parent and y in parent and find(x) == find(y)
    return [ratio[x] / ratio[y] if linked(x, y) else -1.0 for x, y in queries]


# --- provided: do not edit ---
def run_conversions(facts: list[list], queries: list[list[str]]) -> list[float]:
    # Floats differ in the last bits depending on the order of the multiplications: compare at 6 decimals.
    return [round(x, 6) for x in convert(facts, queries)]

This is weighted union-find: each link carries a conversion factor, and a unit's factor to its root is the product along its path. Path compression must multiply as it flattens, or a unit moved under the root keeps the factor to its old parent. A fresh search per query costs O(n) each time; here a query is two finds. Union by size keeps the recursion shallow. Traps: an unknown unit gives -1.0 even against itself, and so do units in different groups.