Subsequence With the Minimum Score - Problem

You're given two strings s and t, and your goal is to transform t into a subsequence of s by removing some characters from t.

Here's the challenge: minimize the "removal cost" of making this transformation!

How scoring works:

  • If you don't remove any characters: score = 0
  • If you remove characters at indices left (minimum) to right (maximum): score = right - left + 1

The key insight is that you want to remove characters in the most compact range possible. For example, removing characters at indices [2,3,4] costs 3, while removing [1,5,9] costs 9!

Goal: Return the minimum possible score to make t a subsequence of s.

Remember: A subsequence maintains the relative order of characters, like "ace" from "abcde".

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "abacaba", t = "bzaa"
โ€บ Output: 1
๐Ÿ’ก Note: We can remove 'z' (index 1) from t to get "baa", which is a subsequence of s. The score is 1-1+1 = 1.
example_2.py โ€” No Removal Needed
$ Input: s = "cde", t = "xyz"
โ€บ Output: 3
๐Ÿ’ก Note: No characters of t exist in s, so we must remove all characters. Score = 2-0+1 = 3.
example_3.py โ€” Already Valid
$ Input: s = "abcde", t = "ace"
โ€บ Output: 0
๐Ÿ’ก Note: t is already a subsequence of s, so no removal needed. Score = 0.

Visualization

Tap to expand
Original Manuscript (t)"a b X Y Z c d"Keep Start"a b"Remove Middle"X Y Z"Keep End"c d"Final Result"a b c d" (valid subsequence!)Cost = length of removed section = 3
Understanding the Visualization
1
Identify Matching Start
Find how much of the beginning already matches the target
2
Identify Matching End
Find how much of the ending already matches the target
3
Minimize Middle Removal
Remove the smallest middle section to connect start and end
4
Verify Solution
Ensure the remaining text forms a valid subsequence
Key Takeaway
๐ŸŽฏ Key Insight: The optimal solution always removes a contiguous middle section, maximizing the matching prefix and suffix portions we can keep.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n log n)

O(n) preprocessing + O(log n) binary search iterations ร— O(n) validation per iteration

n
2n
โšก Linearithmic
Space Complexity
O(n)

Space for left and right prefix arrays

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค s.length, t.length โ‰ค 105
  • s and t consist of only lowercase English letters
  • Memory limit: 256 MB
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 24
52.0K Views
High Frequency
~25 min Avg. Time
1.6K 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