#2391
Minimum Amount of Time to Collect Garbage
MediumArrayStringPrefix SumPrefix SumArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach focuses on minimizing the number of houses visited by each truck. We only need to find the last house for each type of garbage and sum the travel times accordingly, leading to a more efficient solution.
⚙️
Algorithm
3 steps- 1Step 1: Initialize total time to the sum of the lengths of all garbage strings (this accounts for collection time).
- 2Step 2: For each type of garbage ('M', 'P', 'G'), find the last index where that type exists and sum the travel times up to that index.
- 3Step 3: Return the total time.
solution.py9 lines
1def minTimeToCollectGarbage(garbage, travel):
2 total_time = sum(len(g) for g in garbage)
3 for g in 'MPG':
4 last_index = 0
5 for i in range(len(garbage)):
6 if g in garbage[i]:
7 last_index = i
8 total_time += sum(travel[i] for i in range(last_index))
9 return total_timeℹ
Complexity note: The time complexity is O(n) because we only iterate through the garbage array a limited number of times, making it efficient.
- 1Only visit houses with garbage to minimize travel time.
- 2Collect all garbage types in a single pass to optimize performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.