Subsequence With the Minimum Score Problem
Description
LeetCode Problem 2565.
You are given two strings s and t.
You are allowed to remove any number of characters from the string t.
The score of the string is 0 if no characters are removed from the string t, otherwise:
- Let
leftbe the minimum index among all removed characters. - Let
rightbe the maximum index among all removed characters.
Then the score of the string is right - left + 1.
Return the minimum possible score to make t a subsequence of s.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
Example 1:
Input: s = "abacaba", t = "bzaa"
Output: 1
Explanation: In this example, we remove the character "z" at index 1 (0-indexed).
The string t becomes "baa" which is a subsequence of the string "abacaba" and the score is 1 - 1 + 1 = 1.
It can be proven that 1 is the minimum score that we can achieve.
Example 2:
Input: s = "cde", t = "xyz"
Output: 3
Explanation: In this example, we remove characters "x", "y" and "z" at indices 0, 1, and 2 (0-indexed).
The string t becomes "" which is a subsequence of the string "cde" and the score is 2 - 0 + 1 = 3.
It can be proven that 3 is the minimum score that we can achieve.
Constraints:
1 <= s.length, t.length <= 10^5sandtconsist of only lowercase English letters.
Solution
Approach: Prefix and Suffix Matching + Binary Search
Deleting a whole window t[left..right] is always at least as good as deleting scattered characters, and the score only depends on the window length. So we look for the shortest window such that the part of t before it and the part after it both fit into s as subsequences without overlapping.
Precompute f[i], the smallest index in s where the prefix t[0..i] finishes matching greedily from the left, and g[i], the largest index in s where the suffix t[i..n-1] starts matching greedily from the right. A window of length x starting at k works when f[k-1] < g[k+x] (treat a missing side as -1 or m+1).
If a window of length x works, any longer window works too, so we binary search the smallest valid x, checking every start position in each step.
Complexity: time O(n log n), space O(n), where n is the length of t.
from math import inf
class Solution:
def minimumScore(self, s: str, t: str) -> int:
def check(x):
for k in range(n):
i, j = k - 1, k + x
l = f[i] if i >= 0 else -1
r = g[j] if j < n else m + 1
if l < r:
return True
return False
m, n = len(s), len(t)
f = [inf] * n
g = [-1] * n
i, j = 0, 0
while i < m and j < n:
if s[i] == t[j]:
f[j] = i
j += 1
i += 1
i, j = m - 1, n - 1
while i >= 0 and j >= 0:
if s[i] == t[j]:
g[j] = i
j -= 1
i -= 1
lo, hi = 0, n
while lo < hi:
mid = (lo + hi) >> 1
if check(mid):
hi = mid
else:
lo = mid + 1
return lo