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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code