#2167

Minimum Time to Remove All Cars Containing Illegal Goods

Hard
StringDynamic ProgrammingDynamic ProgrammingPrefix SumSuffix Array
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach involves calculating the minimum time to remove illegal cars using prefix and suffix arrays. This allows us to efficiently compute the time required without redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create an array withoutFirst where withoutFirst[i] stores the minimum time to remove all illegal cars from the suffix starting at index i without using type 1 operations.
  2. 2Step 2: Create an array onlyFirst where onlyFirst[i] stores the minimum time to remove all illegal cars from the prefix ending at index i using only type 1 operations.
  3. 3Step 3: Combine results from both arrays to find the minimum time to remove all illegal cars.
solution.py16 lines
1def minTimeToRemoveCars(s):
2    n = len(s)
3    withoutFirst = [0] * n
4    onlyFirst = [0] * n
5    for i in range(n - 1, -1, -1):
6        if s[i] == '1':
7            withoutFirst[i] = 2 + (withoutFirst[i + 1] if i + 1 < n else 0)
8        else:
9            withoutFirst[i] = withoutFirst[i + 1] if i + 1 < n else 0
10    for i in range(n):
11        if s[i] == '1':
12            onlyFirst[i] = i + 1
13        else:
14            onlyFirst[i] = onlyFirst[i - 1] if i > 0 else 0
15    min_time = min(onlyFirst[i] + withoutFirst[i + 1] for i in range(n - 1))
16    return min_time

Complexity note: This complexity is due to the linear traversal of the string to fill the prefix and suffix arrays.

  • 1Removing from the ends is cheaper than from the middle.
  • 2Using prefix and suffix calculations can reduce redundant operations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.