Minimum Time to Remove All Cars Containing Illegal Goods — LeetCode 2167 Python Solution

HardStringDynamic Programming
Problem
#2167
Reading time
3 min

The problem

You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods.

Example

Input
s = "1100101"
Output
5
Explanation
One way to remove all the cars containing illegal goods from the sequence is to

Python solution

Python
class Solution:
    def minimumTime(self, s: str) -> int:
        n = len(s)
        pre = [0] * (n + 1)
        suf = [0] * (n + 1)
        for i, c in enumerate(s):
            pre[i + 1] = pre[i] if c == '0' else min(pre[i] + 2, i + 1)
        for i in range(n - 1, -1, -1):
            suf[i] = suf[i + 1] if s[i] == '0' else min(suf[i + 1] + 2, n - i)
        return min(a + b for a, b in zip(pre[1:], suf[1:]))

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2167. Minimum Time to Remove All Cars Containing Illegal Goods is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2167. Minimum Time to Remove All Cars Containing Illegal Goods?
LeetCode 2167. Minimum Time to Remove All Cars Containing Illegal Goods is rated Hard on LeetCode.
What topics does LeetCode 2167. Minimum Time to Remove All Cars Containing Illegal Goods cover?
LeetCode 2167. Minimum Time to Remove All Cars Containing Illegal Goods is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview