Minimum Time to Remove All Cars Containing Illegal Goods - 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.

As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times:

  • Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time.
  • Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit of time.
  • Remove a train car from anywhere in the sequence which takes 2 units of time.

Return the minimum time to remove all the cars containing illegal goods.

Note: An empty sequence of cars is considered to have no cars containing illegal goods.

Input & Output

Example 1 — Basic Mixed Case
$ Input: s = "1100101"
Output: 5
💡 Note: Remove the first 2 cars from left (2 units), remove the middle '1' at index 4 individually (2 units), and remove the last car from right (1 unit). Total: 2 + 2 + 1 = 5.
Example 2 — All Illegal
$ Input: s = "11111"
Output: 5
💡 Note: Remove all 5 cars from either left or right end, each taking 1 unit of time. Total: 5 units.
Example 3 — No Illegal Cars
$ Input: s = "0000"
Output: 0
💡 Note: No cars contain illegal goods, so no removal is needed. Total: 0 units.

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is either '0' or '1'

Visualization

Tap to expand
Train Car Removal ProblemInput: "1100101" (1=illegal, 0=legal)1100101Remove from LeftCost: 1 unit per carRemove from MiddleCost: 2 units per carRemove from RightCost: 1 unit per carOptimal Strategy for "1100101":Remove first 2 cars from left (2 units)Remove middle '1' at position 4 individually (2 units)Remove last car from right (1 unit)Total Cost: 2 + 2 + 1 = 5 units
Understanding the Visualization
1
Input
Binary string representing train cars (1=illegal, 0=legal)
2
Operations
Remove from left (1 unit), right (1 unit), or middle (2 units)
3
Goal
Find minimum time to remove all illegal cars
Key Takeaway
🎯 Key Insight: It's often cheaper to remove entire segments from the ends rather than individual cars from the middle
Asked in
Google 12 Meta 8 Amazon 6 Microsoft 4
23.4K Views
Medium Frequency
~25 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