Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Subsequence With the Minimum Score

Updated
5 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2565" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 left be the minimum index among all removed characters. Let right be 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 <= 105 s and t consist of only lowercase English letters.

Explanation

Here's the breakdown of the solution:

  • Find Leftmost Matches: Iterate through t. For each character in t, find the earliest index in s where it appears after matching the previous characters of t. Store these indices.
  • Find Rightmost Matches: Iterate through t in reverse. For each character in t, find the latest index in s where it appears before matching the succeeding characters of t. Store these indices.
  • Minimize the Score: Iterate through all possible removal ranges in t. For each range, check if the remaining characters in t form a subsequence of s using the precomputed leftmost and rightmost match indices. Calculate and minimize the score for each valid range.

  • Runtime Complexity: O(m*n), where n is the length of s and m is the length of t.

  • Storage Complexity: O(m), where m is the length of t.
def solve():
    s = input()
    t = input()
    n = len(s)
    m = len(t)

    leftmost = [-1] * m
    rightmost = [-1] * m

    # Calculate leftmost matches
    s_ptr = 0
    for t_ptr in range(m):
        while s_ptr < n:
            if s[s_ptr] == t[t_ptr]:
                leftmost[t_ptr] = s_ptr
                s_ptr += 1
                break
            s_ptr += 1
        else:
            break # Could not find match

    # Calculate rightmost matches
    s_ptr = n - 1
    for t_ptr in range(m - 1, -1, -1):
        while s_ptr >= 0:
            if s[s_ptr] == t[t_ptr]:
                rightmost[t_ptr] = s_ptr
                s_ptr -= 1
                break
            s_ptr -= 1
        else:
            break

    ans = m
    for left in range(m + 1):
        for right in range(left, m + 1):
            # Check if t[:left] + t[right:] is a subsequence of s

            # Check left part
            valid = True
            if left > 0:
                prev_s_index = -1
                t_index = 0
                while t_index < left:
                    found = False
                    for s_index in range(prev_s_index + 1, n):
                        if s[s_index] == t[t_index]:
                            prev_s_index = s_index
                            found = True
                            break
                    if not found:
                        valid = False
                        break
                    t_index += 1
                if not valid:
                    continue

            # Check right part
            if right < m:
                prev_s_index = -1
                t_index = right
                while t_index < m:
                    found = False
                    for s_index in range(prev_s_index + 1, n):
                        if s[s_index] == t[t_index]:
                            prev_s_index = s_index
                            found = True
                            break
                    if not found:
                        valid = False
                        break
                    t_index += 1
                if not valid:
                    continue

            if left == 0 and right == m:
                if "" not in s:
                    continue

            if left == right and left != m:

                l = 0
                r = 0
                isValid = False
                t_l = t[:left]
                t_r = t[right:]
                combined = t_l + t_r


                if len(combined) == 0:
                     ans = min(ans, right - left + 1)
                     continue

                s_ptr = 0
                t_ptr = 0

                while s_ptr < len(s) and t_ptr < len(combined):
                    if s[s_ptr] == combined[t_ptr]:
                        t_ptr += 1
                    s_ptr += 1

                if t_ptr == len(combined):

                   ans = min(ans, right - left + 1)

            elif left != right:
                ans = min(ans, right - left)


    print(ans)


    # Code
    ```python
    def solve():    s = input()
    t = input()
    n = len(s)
    m = len(t)

    leftmost = [-1] * m
    rightmost = [-1] * m

    # Calculate leftmost matches
    s_ptr = 0
    for t_ptr in range(m):
        while s_ptr < n:
            if s[s_ptr] == t[t_ptr]:
                leftmost[t_ptr] = s_ptr
                s_ptr += 1
                break
            s_ptr += 1
        else:
            break # Could not find match

    # Calculate rightmost matches
    s_ptr = n - 1
    for t_ptr in range(m - 1, -1, -1):
        while s_ptr >= 0:
            if s[s_ptr] == t[t_ptr]:
                rightmost[t_ptr] = s_ptr
                s_ptr -= 1
                break
            s_ptr -= 1
        else:
            break

    ans = m
    for left in range(m + 1):
        for right in range(left, m + 1):
            # Check if t[:left] + t[right:] is a subsequence of s

            # Check left part
            valid = True
            if left > 0:
                prev_s_index = -1
                t_index = 0
                while t_index < left:
                    found = False
                    for s_index in range(prev_s_index + 1, n):
                        if s[s_index] == t[t_index]:
                            prev_s_index = s_index
                            found = True
                            break
                    if not found:
                        valid = False
                        break
                    t_index += 1
                if not valid:
                    continue

            # Check right part
            if right < m:
                prev_s_index = -1
                t_index = right
                while t_index < m:
                    found = False
                    for s_index in range(prev_s_index + 1, n):
                        if s[s_index] == t[t_index]:
                            prev_s_index = s_index
                            found = True
                            break
                    if not found:
                        valid = False
                        break
                    t_index += 1
                if not valid:
                    continue

            if left == 0 and right == m:
                ans = min(ans, m)
                continue

            ans = min(ans, right - left)

    print(ans)

solve()

More from this blog

C

Chatmagic blog

2894 posts