Minimum Time to Make Rope Colorful (LeetCode 1578): Solution and Explanation

Medium
Array
String
Dynamic Programming
Greedy

Balloons hang on a rope, each with a color and a removal time. Remove balloons so that no two neighbours share a color, and return the smallest total removal time.

Intuition

Equal neighbours only ever appear inside a run of consecutive balloons with the same color. Removing balloons from one run never changes which balloons are neighbours in another run, so each run can be solved on its own.

A run of k balloons must end with exactly one balloon left. To spend as little time as possible, the survivor should be the balloon that is slowest to remove, so the run costs its total time minus its largest time.

You do not need to find runs first. Walk the rope once and carry the largest time in the current run. Each new balloon of the same color forces one pop: the cheaper of it and the current keeper.

Approach: One pass, keep the most expensive balloon

  1. Set total = 0 and keep = neededTime[0].
  2. For each i from 1, if colors[i] differs from colors[i - 1], a new run starts: set keep = neededTime[i].
  3. Otherwise, if neededTime[i] < keep, pop balloon i and add its time to total.
  4. Otherwise pop the current keeper: add keep to total and set keep = neededTime[i].
  5. Return total.

Step-by-step example

colors = "abaac", neededTime = [1,2,3,4,5]
  1. Balloon 0 is 'a' with time 1, so keep = 1.
  2. Balloon 1 is 'b', a new color, so keep = 2. Balloon 2 is 'a', again new, so keep = 3.
  3. Balloon 3 is 'a', the same as balloon 2. Its time 4 is not less than keep = 3, so balloon 2 pops: total = 3, keep = 4.
  4. Balloon 4 is 'c', a new run, keep = 5.
  5. The scan ends and the answer is 3.

Code: Python, Java, C++

1class Solution:
2    def minCost(self, colors: str, neededTime: List[int]) -> int:
3        total = 0
4        keep = neededTime[0]
5        for i in range(1, len(colors)):
6            if colors[i] != colors[i - 1]:
7                keep = neededTime[i]
8            elif neededTime[i] < keep:
9                total += neededTime[i]
10            else:
11                total += keep
12                keep = neededTime[i]
13        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each balloon is visited once and does a constant amount of work.

Space

O(1)

Only the running total and the keeper's time are stored.

Other approaches

Group runs, then sum minus max (time O(n), space O(1))

Split the rope into maximal runs of one color, and for each run add the sum of its times minus the largest time. It is the same greedy idea written in two steps.

Dynamic programming on the last kept balloon (time O(n), space O(n))

Let dp[i] be the best cost for the prefix ending with balloon i kept. It works but is more machinery than the problem needs, because runs never interact.

Common mistakes

  • Popping the newer balloon every time. When the new balloon is slower to remove, the cheaper earlier keeper should go instead, and the new one becomes the keeper.
  • Comparing against the previous balloon's own time instead of the run's keeper. After a pop, the keeper may be further back in the run.
  • Forgetting to reset the keeper when the color changes, which lets a value from one run leak into the next.
  • Thinking a run of three or more needs special handling. Each extra balloon causes exactly one pop, so the same rule covers any run length.

Frequently asked questions

Why keep the balloon with the largest time?

A run of k balloons must lose k - 1 of them. The total removed is the run's sum minus the one survivor, which is smallest when the survivor has the largest time.

Is this a dynamic programming problem?

It is listed under dynamic programming and greedy, but the greedy observation removes any need for a table. One pass with two variables is enough.

What happens with ties?

If the new balloon has the same time as the keeper, either one can be popped. The total is the same.