Subsequence With the Minimum Score — LeetCode 2565 Python Solution

HardTwo PointersStringBinary Search
Problem
#2565
Reading time
5 min

The problem

You are given two strings s and t. You are allowed to remove any number of characters from the string t.

Example

Input
s = "abacaba", t = "bzaa"
Output
1
Explanation
In this example, we remove the character "z" at index 1 (0-indexed).

Python solution

Python
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

        return bisect_left(range(n + 1), True, key=check)

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2565. Subsequence With the Minimum Score is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2565. Subsequence With the Minimum Score?
LeetCode 2565. Subsequence With the Minimum Score is rated Hard on LeetCode.
What is the time complexity of LeetCode 2565. Subsequence With the Minimum Score?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2565. Subsequence With the Minimum Score?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2565. Subsequence With the Minimum Score cover?
LeetCode 2565. Subsequence With the Minimum Score is tagged Two Pointers, String and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview