#3528

Unit Conversion I

Medium
Depth-First SearchBreadth-First SearchGraph TheoryGraph TraversalDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using BFS or DFS, we can efficiently traverse the conversion graph from the base unit, multiplying conversion factors along the way to compute equivalent units.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a graph from the conversions array where each unit points to its conversions.
  2. 2Step 2: Perform a BFS starting from unit 0, updating the equivalent units using the conversion factors.
  3. 3Step 3: Return the results modulo 10^9 + 7.
solution.py17 lines
1from collections import defaultdict, deque
2
3def unitConversion(conversions):
4    graph = defaultdict(list)
5    for src, tgt, factor in conversions:
6        graph[src].append((tgt, factor))
7    n = len(conversions) + 1
8    baseUnitConversion = [0] * n
9    baseUnitConversion[0] = 1
10    queue = deque([0])
11    while queue:
12        unit = queue.popleft()
13        for tgt, factor in graph[unit]:
14            if baseUnitConversion[tgt] == 0:
15                queue.append(tgt)
16            baseUnitConversion[tgt] = (baseUnitConversion[tgt] + baseUnitConversion[unit] * factor) % (10**9 + 7)
17    return baseUnitConversion

Complexity note: Each unit is processed once, leading to linear complexity.

  • 1Graph traversal is key to solving unit conversions efficiently.
  • 2Understanding the relationships between units helps in structuring the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.