There are n types of units indexed from 0 to n - 1. You are given a 2D integer array conversions of length n - 1, where conversions[i] = [sourceUnit_i, targetUnit_i, conversionFactor_i]. This indicates that a single unit of type sourceUnit_i is equivalent to conversionFactor_i units of type targetUnit_i.

You are also given a 2D integer array queries of length q, where queries[i] = [unitA_i, unitB_i]. Return an array answer of length q where answer[i] is the number of units of type unitB_i equivalent to 1 unit of type unitA_i, and can be represented as p/q where p and q are coprime.

Return each answer[i] as p * q^(-1) mod (10^9 + 7), where q^(-1) represents the multiplicative inverse of q modulo 10^9 + 7.

Input & Output

Example 1 — Basic Conversion Chain
$ Input: conversions = [[0,1,3],[1,2,2]], queries = [[0,2],[1,0]]
Output: [6,333333336]
💡 Note: For query [0,2]: 0→1 (×3) then 1→2 (×2), so 1 unit of type 0 = 6 units of type 2. For query [1,0]: reverse conversion 1→0 is 1/3, which as modular arithmetic gives 333333336.
Example 2 — Direct Conversion
$ Input: conversions = [[0,1,5]], queries = [[0,1],[1,0]]
Output: [5,400000003]
💡 Note: Direct conversions: 0→1 gives 5/1 = 5. Reverse 1→0 gives 1/5, and the modular inverse of 5 mod (10^9+7) is 400000003.
Example 3 — No Path Available
$ Input: conversions = [[0,1,2]], queries = [[0,2]]
Output: [0]
💡 Note: No conversion path exists from unit 0 to unit 2, so return 0.

Constraints

  • 1 ≤ n ≤ 100
  • conversions.length == n - 1
  • 1 ≤ queries.length ≤ 100
  • 1 ≤ conversionFactori ≤ 105

Visualization

Tap to expand
Unit Conversion II: Graph-Based Path FindingInput Conversions[0,1,3] → 0 to 1: ×3[1,2,2] → 1 to 2: ×2Query: [0,2]012×3×2Path Calculation0 → 1 → 21 × 3 × 2 = 6Result: 6/1 = 6Output: [6]
Understanding the Visualization
1
Input Graph
Conversions [[0,1,3],[1,2,2]] create connected units
2
Path Search
Find path from query unit A to unit B
3
Ratio Calculation
Multiply conversion factors along the path
Key Takeaway
🎯 Key Insight: Model conversions as a graph and use DFS to find conversion paths between units
Asked in
Google 25 Facebook 20 Amazon 15
25.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen