Approach
Breadth-first search
For Unit Conversion II, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 38 lines of Python from the credited upstream file 3535.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def queryConversions(3 self,4 conversions: list[list[int]],5 queries: list[list[int]]6 ) -> list[int]:7 self.MOD = 1_000_000_0078 units = self._baseUnitConversions(conversions)9 10 return [units[v] * self._modPow(units[u], self.MOD - 2) % self.MOD11 for u, v in queries]12 13 14 def _baseUnitConversions(self, conversions: list[list[int]]) -> list[int]:15 n = len(conversions) + 116 res = [0] * n17 res[0] = 118 q = collections.deque([0])19 graph = [[] for _ in range(n)]20 21 for u, v, factor in conversions:22 graph[u].append((v, factor))23 24 while q:25 u = q.popleft()26 for v, factor in graph[u]:27 res[v] = (res[u] * factor) % self.MOD28 q.append(v)29 30 return res31 32 def _modPow(self, x: int, n: int) -> int:33 if n == 0:34 return 135 if n % 2 == 1:36 return x * self._modPow(x, n - 1) % self.MOD37 return self._modPow(x * x % self.MOD, n 2)38