KatInterview

Cheapest Type Transformation Path

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgraphsshortest-pathdijkstra

Last updated

Tests shortest-path reasoning on a weighted directed graph, including source-caching strategy, zero-cost edges, unreachable nodes, and same-source queries.

Cheapest Type Transformation Path

You are building a data pipeline that converts values between named primitive types. A set of directed conversion rules describes how to move from one type to another, each at some non-negative integer cost. Given a batch of queries, find the minimum total cost to transform a source type into a target type along any chain of conversions.

Input

  • rules: a list of [from_type, to_type, cost] triples. Both from_type and to_type are strings; cost is a non-negative integer. Multiple rules may share the same pair of types — treat each as an independent directed edge.
  • queries: a list of [source, target] pairs of strings.

Task

For each query [source, target], return the minimum total cost of any sequence of conversions that starts at source and ends at target. If no such sequence exists, return -1.

Rules and edge cases

  • A type can always "convert" to itself at zero cost, even if no rule says so — including types that appear in no rule at all.
  • Conversions are directed: a rule [A, B, cost] does not imply a rule from B to A.
  • If source cannot reach target through any chain of rules, the answer is -1.
  • Costs are non-negative, so a path that uses more steps is never cheaper than one that skips them.

Constraints

  • Number of distinct types: up to 10 000
  • Number of rules: up to 100 000
  • Number of queries: up to 100 000
  • Each cost satisfies 0 ≤ cost ≤ 10 000
  • Type names are non-empty strings

Examples

Example 1

Input: cheapest_conversion_path([['a', 'b', 4], ['a', 'c', 1], ['c', 'b', 1], ['b', 'd', 2]], [['a', 'd'], ['a', 'b'], ['d', 'a'], ['x', 'x']])

Output: [4, 2, -1, 0]

Example 2

Input: cheapest_conversion_path([['same', 'same', 7], ['p', 'q', 0], ['p', 'q', 5]], [['same', 'same'], ['p', 'q'], ['q', 'p']])

Output: [0, 0, -1]

Hints

Hint 1

Model types as nodes and conversion rules as weighted directed edges, then think about which classic single-source shortest-path algorithm applies when all weights are non-negative.

Hint 2

Many queries may share the same source type. Running a full shortest-path search once per source and caching the result turns repeated queries into O(1) lookups.

Hint 3

Handle the same-node case carefully: the cost from any type to itself is always 0, regardless of whether that type appears in any rule.