Unit Conversion II
Learn this problemProblem statement
There are n unit types indexed from 0 to n - 1. The array conversions has length n - 1. Each entry [sourceUnit, targetUnit, conversionFactor] means that one unit of sourceUnit is equivalent to conversionFactor units of targetUnit.
Each entry [unitA, unitB] in queries asks how many units of unitB are equivalent to one unit of unitA. The exact answer can be written as a reduced fraction p / q. Return p * q^(-1) modulo 10^9 + 7, where q^(-1) is the multiplicative inverse of q modulo 10^9 + 7.
Return one answer for every query in the same order. It is guaranteed that unit 0 can be converted uniquely into every other unit by combining forward conversions and inverse conversions.
Function
queryConversions(conversions: int[][], queries: int[][]) → int[]Examples
Example 1
conversions = [[0,1,2],[0,2,6]]queries = [[1,2],[1,0]]return = [3,500000004]One unit of type 1 is half a unit of type 0. It is therefore equivalent to 3 units of type 2. The inverse of 2 modulo 10^9 + 7 is 500000004.
Example 2
conversions = [[0,1,2],[0,2,6],[0,3,8],[2,4,2],[2,5,4],[3,6,3]]queries = [[1,2],[0,4],[6,5],[4,6],[6,1]]return = [3,12,1,2,83333334]Relative to unit 0, the conversion amounts are 2, 6, 8, 12, 24, and 24 for units 1 through 6. Dividing the destination amount by the source amount answers each query. The final query is 2 / 24 = 1 / 12, whose modular value is 83333334.
Constraints
2 <= n <= 10^5conversions.length = n - 1- Each conversion has the form
[sourceUnit, targetUnit, conversionFactor]. 0 <= sourceUnit, targetUnit < n1 <= conversionFactor <= 10^91 <= queries.length <= 10^5- Each query has the form
[unitA, unitB]with both unit indices in[0, n - 1]. - Unit
0has exactly one conversion path to every unit when conversion edges are treated as bidirectional.
More Apple problems
- Insert IntervalPHONE SCREEN · Seen Jul 2026
- Group Transitive String AliasesPHONE SCREEN · Seen Jul 2026
- Design Task ManagerPHONE SCREEN · Seen Jul 2026
- Two-Color an Undirected GraphPHONE SCREEN · Seen Jul 2026
- Word Search IIPHONE SCREEN · Seen Jul 2026
- Phone DirectoryPHONE SCREEN · Seen Jul 2026
- Product Except Self With ZerosONSITE INTERVIEW · Seen Jul 2026
- Subset Sum PossibleONSITE INTERVIEW · Seen Jul 2026