Minimum Amount of Time to Collect Garbage — LeetCode 2391 Python Solution
- Problem
- #2391
- Pattern
- Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively.
Example
- Input
- garbage = ["G","P","GP","GG"], travel = [2,4,3]
- Output
- 21
- Explanation
- The paper garbage truck:
Python solution
class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
last = {}
ans = 0
for i, s in enumerate(garbage):
ans += len(s)
for c in s:
last[c] = i
ts = 0
for i, t in enumerate(travel, 1):
ts += t
ans += sum(ts for j in last.values() if i == j)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(k), where n and k are the number and types of garbage, respectively auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2391. Minimum Amount of Time to Collect Garbage is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2391. Minimum Amount of Time to Collect Garbage?
- LeetCode 2391. Minimum Amount of Time to Collect Garbage is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2391. Minimum Amount of Time to Collect Garbage?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2391. Minimum Amount of Time to Collect Garbage?
- The Python solution on this page uses O(k), where n and k are the number and types of garbage, respectively auxiliary space.
- What topics does LeetCode 2391. Minimum Amount of Time to Collect Garbage cover?
- LeetCode 2391. Minimum Amount of Time to Collect Garbage is tagged Array, String and Prefix Sum on LeetCode.