[LeetCode] Unit Conversion I

3528. Unit Conversion I

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] = [sourceUniti, targetUniti, conversionFactori]. This indicates that a single unit of type sourceUniti is equivalent to conversionFactori units of type targetUniti.

Return an array baseUnitConversion of length n, where baseUnitConversion[i] is the number of units of type i equivalent to a single unit of type 0. Since the answer may be large, return each baseUnitConversion[i] modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
vector<int> baseUnitConversions(vector<vector<int>>& conversions) {
long long n = conversions.size() + 1, mod = 1e9 + 7;
vector<vector<pair<long long,long long>>> adj(n);
for(auto& c : conversions) {
adj[c[0]].push_back({c[1], c[2]});
}
vector<int> res(n,1);
queue<int> q; q.push(0);
while(q.size()) {
int u = q.front(); q.pop();
for(auto& [v,w] : adj[u]) {
q.push(v);
res[v] = w * res[u] % mod;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/04/27/PS/LeetCode/unit-conversion-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.