Minimum Amount of Time to Collect Garbage - Problem

You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the i-th house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively.

Picking up one unit of any type of garbage takes 1 minute.

You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1.

There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house.

Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.

Return the minimum number of minutes needed to pick up all the garbage.

Input & Output

Example 1 — Basic Case
$ Input: garbage = ["G","P","GP","GG"], travel = [2,4,3]
Output: 21
💡 Note: G truck: 4 units (1+0+1+2) + 9 travel time (2+4+3 to reach house 3) = 13 min. P truck: 2 units (0+1+1+0) + 6 travel time (2+4 to reach house 2) = 8 min. M truck: 0 units + 0 travel = 0 min. Total = 13+8+0 = 21 minutes.
Example 2 — All Types at First House
$ Input: garbage = ["MPG","M","P","GPG"], travel = [1,3,2]
Output: 37
💡 Note: M truck: 2 units (1+1+0+0) + 3 travel time (1+3 to house 1) = 5 min. P truck: 3 units (1+0+1+1) + 6 travel time (1+3+2 to house 3) = 9 min. G truck: 3 units (1+0+0+2) + 6 travel time to house 3 = 9 min. Total = 5+9+9 = 23 minutes.
Example 3 — Single House
$ Input: garbage = ["MMM"], travel = []
Output: 3
💡 Note: Only M truck needs to work: 3 units of metal at house 0, no travel required. Total = 3 minutes.

Constraints

  • 1 ≤ garbage.length ≤ 105
  • 1 ≤ garbage[i].length ≤ 10
  • garbage[i] consists of only the letters 'M', 'P', and 'G'
  • 1 ≤ travel.length ≤ 104
  • 1 ≤ travel[i] ≤ 100
  • travel.length == garbage.length - 1

Visualization

Tap to expand
Garbage Collection Problem OverviewHouse 0GHouse 1PHouse 2GPHouse 3GGtravel=2travel=4travel=3G Truck: 4+9=13P Truck: 2+6=8M Truck: 0+0=0Last house: 3Last house: 2No metal foundTotal Time: 13 + 8 + 0 = 21 minutesEach truck works sequentially, not in parallel
Understanding the Visualization
1
Input
Houses with mixed garbage types and travel times between houses
2
Process
Each truck finds its optimal route to last required house
3
Output
Sum of all truck times (pickup + travel)
Key Takeaway
🎯 Key Insight: Each truck only travels to its last pickup location, not every house
Asked in
Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen