call(back)
Algorithms & Data StructuresmediumSign in to star problems

Unit Conversion I

There are n unit types, numbered 0 to n - 1, and unit 0 is the base. Each conversion [source, target, factor] means one unit of source equals factor units of target. The conversions form a tree rooted at 0, and every factor is at least 1.

Return ans where ans[i] is how many units of type i equal one unit of type 0, modulo 1_000_000_007.

baseUnitConversions(3, [[0, 1, 2], [1, 2, 3]])  ->  [1, 2, 6]

Products can exceed 2^53 before the modulo — in JavaScript, do the arithmetic in BigInt (the harness converts your answers back to numbers).

Hints

Hint 1

One traversal from the root: ans[0] = 1 and ans[child] = ans[parent] × factor (mod p).

Hint 2

Use an explicit stack; with up to 10^5 units the tree can be a path, and recursion that deep overflows.

Asked at