FastPrepUnit Conversion II
Problems/Unit Conversion II

Unit Conversion II

Apple logoApple● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report identifies this exact public task but does not restate its details. The judged core task matches that identity at about 98%.

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^5
  • conversions.length = n - 1
  • Each conversion has the form [sourceUnit, targetUnit, conversionFactor].
  • 0 <= sourceUnit, targetUnit < n
  • 1 <= conversionFactor <= 10^9
  • 1 <= queries.length <= 10^5
  • Each query has the form [unitA, unitB] with both unit indices in [0, n - 1].
  • Unit 0 has exactly one conversion path to every unit when conversion edges are treated as bidirectional.

More Apple problems

  • Evaluate DivisionPHONE SCREEN · Seen Nov 2026
  • Reverse a Linked ListPHONE SCREEN · Seen Nov 2026
  • Validate a BST with a Custom ComparisonPHONE SCREEN · Seen Nov 2026
All Apple interview questionsSee Apple hiring insights
Saved
class Solution {
    public int[] queryConversions(int[][] conversions, int[][] queries) {
        // Write your code here.
    }
}
Checking account…