Subsequence With the Minimum Score - Problem

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).

Input & Output

Example 1 — Basic Case
$ Input: s = "abacaba", t = "bzc"
Output: 2
💡 Note: Remove "bz" from t, leaving "c". The character "c" exists in s as a subsequence. Score = 1 - 0 + 1 = 2.
Example 2 — Already Subsequence
$ Input: s = "abcdef", t = "ace"
Output: 0
💡 Note: t is already a subsequence of s, so no characters need to be removed. Score = 0.
Example 3 — Remove Middle
$ Input: s = "xyz", t = "xay"
Output: 1
💡 Note: Remove "a" from position 1, leaving "xy" which is a subsequence of "xyz". Score = 1 - 1 + 1 = 1.

Constraints

  • 1 ≤ s.length, t.length ≤ 105
  • s and t consist of only lowercase English letters

Visualization

Tap to expand
Subsequence With Minimum Score INPUT String s = "abacaba" a 0 b 1 a 2 c 3 a 4 b 5 a 6 String t = "bzc" b 0 z 1 c 2 Goal: Remove chars from t to make it subsequence of s with minimum score Score Formula: right - left + 1 ALGORITHM STEPS 1 Prefix Match Match t from left in s t[0]='b' found at s[1] 2 Suffix Match Match t from right in s t[2]='c' found at s[3] 3 Two Pointers Find optimal removal by sliding window 4 Calculate Score Min removal: index 1 Remove 'z' only b KEEP z REMOVE c KEEP "bc" is subsequence of "abacaba" FINAL RESULT Removed character: 'z' Position: index 1 Score Calculation: left = 1, right = 1 score = 1 - 1 + 1 = 1 But we need to check: Remove t[1..2] = "zc" OUTPUT 2 Remove "zc" (index 1 to 2) Score = 2 - 1 + 1 = 2 "b" is subseq of s [OK] Key Insight: Use prefix and suffix arrays to precompute matches. prefix[i] stores how many chars of t can be matched using s[0..i]. suffix[j] stores how many chars from end of t match using s[j..n]. Binary search or two pointers to find minimum contiguous removal in t that makes rest a subsequence. TutorialsPoint - Subsequence With the Minimum Score | Optimal Solution
Asked in
Google 12 Microsoft 8 Amazon 6
8.5K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen