Cheapest Type Transformation Path
Trees & GraphsAuto-graded · 17 test casesLast 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. Bothfrom_typeandto_typeare strings;costis 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 fromBtoA. - If
sourcecannot reachtargetthrough 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Modeling the problem as a graph
Each type name is a node. Each rule [A, B, cost] is a weighted directed edge from A to B. Finding the minimum conversion cost from a source to a target is exactly the single-source shortest-path problem on this graph.
Because all costs are non-negative, Dijkstra's algorithm is the right tool. It processes nodes in order of increasing tentative distance and guarantees that the first time a node is finalized, its distance is optimal.
Handling the query batch efficiently
Running a fresh Dijkstra for every one of the 100 000 queries would be far too slow in the worst case. The key observation is that many queries share the same source type. One Dijkstra from a given source computes the shortest distance to every reachable node at once, so all queries with that source can be answered from a single cached result.
The algorithm:
- Build the adjacency list from
rules. - Maintain a
dist_cachemapping each processed source to its full distance dictionary. - For each query, run Dijkstra only if the source is not yet cached; then look up the target in the cached distances.
Edge cases
- Same source and target: the cost is always 0, even for types that appear nowhere in the rules. The code handles this with an explicit check after the cache lookup.
- Multiple rules between the same pair: Dijkstra naturally picks the cheapest relaxation, so parallel edges need no special treatment.
- Unreachable target: the target simply won't appear in the distance dict; return -1.
- Source not in any rule: Dijkstra starts with only the source at distance 0 and never relaxes any edge, leaving all other types unreachable.
Why it is correct
Dijkstra's invariant is that once a node is popped from the min-heap with distance d, no shorter path to it exists (because all edge weights are non-negative, any path through an unvisited node would be at least as long). Stale heap entries — pairs where the stored distance is larger than the current best — are discarded on the spot with the d != dist[node] guard.
Complexity
- Graph construction: O(E), where E is the number of rules.
- Each Dijkstra run: O((E + V) log V) with a binary heap, where V is the number of distinct types reachable from that source.
- Total across all queries: O(S · (E + V) log V + Q), where S is the number of distinct source types actually queried and Q is the total number of queries. In the best case (all queries share one source) S = 1; in the worst case S = min(Q, V).
- Space: O(V + E) for the graph plus O(V) per cached source.
Reference solution
import heapq
from collections import defaultdict
from typing import List
def cheapest_conversion_path(rules: List[List[object]], queries: List[List[str]]) -> List[int]:
# Build adjacency list from the conversion rules.
graph = defaultdict(list)
for from_type, to_type, cost in rules:
graph[from_type].append((to_type, cost))
# Cache the full Dijkstra result (all reachable distances) for each
# source we have already processed. Subsequent queries with the same
# source become a single dict lookup instead of a new search.
dist_cache = {}
results = []
for source, target in queries:
if source not in dist_cache:
# Standard Dijkstra from `source` over the string-node graph.
dist = {source: 0}
heap = [(0, source)]
while heap:
d, node = heapq.heappop(heap)
# Skip stale heap entries.
if d != dist[node]:
continue
for neighbor, cost in graph[node]:
candidate = d + cost
if candidate < dist.get(neighbor, float("inf")):
dist[neighbor] = candidate
heapq.heappush(heap, (candidate, neighbor))
dist_cache[source] = dist
# Same type always costs 0; fall back to -1 if unreachable.
if source == target:
results.append(0)
else:
results.append(dist_cache[source].get(target, -1))
return results