Minimum Time to Activate String Problem
Description
LeetCode Problem 3639.
You are given a string s of length n and an integer array order, where order is a permutation of the numbers in the range [0, n - 1].
Starting from time t = 0, replace the character at index order[t] in s with '*' at each time step.
A substring is valid if it contains at least one '*'.
A string is active if the total number of valid substrings is greater than or equal to k.
Return the minimum time t at which the string s becomes active. If it is impossible, return -1.
Example 1:
Input: s = "abc", order = [1,0,2], k = 2
Output: 0
Explanation:
t order[t] Modified s Valid Substrings Count Active (Count >= k)
0 1 "a*c" "*", "a*", "*c", "a*c" 4 Yes
The string s becomes active at t = 0. Thus, the answer is 0.
Example 2:
Input: s = "cat", order = [0,2,1], k = 6
Output: 2
Explanation:
t order[t] Modified s Valid Substrings Count Active (Count >= k)
0 0 "*at" "*", "*a", "*at" 3 No
1 2 "*a*" "*", "*a", "*a*", "a*", "*" 5 No
2 1 "***" All substrings (contain '*') 6 Yes
The string s becomes active at t = 2. Thus, the answer is 2.
Example 3:
Input: s = "xy", order = [0,1], k = 4
Output: -1
Explanation:
Even after all replacements, it is impossible to obtain k = 4 valid substrings. Thus, the answer is -1.
Constraints:
1 <= n == s.length <= 10^5order.length == n0 <= order[i] <= n - 1sconsists of lowercase English letters.orderis a permutation of integers from 0 ton - 1.1 <= k <= 10^9
Solution
Approach: Binary Search on the Time
Marking more positions never removes a valid substring, so "active at time t" is monotonic in t and we can binary search for the first time it holds.
To test a time t, mark the positions order[0..t]. A substring is valid unless it contains no *, so the number of valid substrings is n * (n + 1) / 2 minus the number of substrings inside the runs of unmarked positions; a run of length L contains L * (L + 1) / 2 of them. The string is active when that count is at least k.
If even the string with every position marked (all n * (n + 1) / 2 substrings valid) has fewer than k valid substrings, return -1.
Complexity: O(n log n) time and O(n) space, where n is the length of s.
class Solution:
def minTime(self, s: str, order: List[int], k: int) -> int:
n = len(s)
total = n * (n + 1) // 2
def active(t: int) -> bool:
star = [False] * n
for i in order[: t + 1]:
star[i] = True
plain = run = 0 # substrings without any '*'
for x in star:
if x:
run = 0
else:
run += 1
plain += run
return total - plain >= k
if total < k:
return -1
lo, hi = 0, n - 1
while lo < hi:
mid = (lo + hi) // 2
if active(mid):
hi = mid
else:
lo = mid + 1
return lo