#2565

Subsequence With the Minimum Score

Hard
Two PointersStringBinary SearchTwo PointersDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(m)
💡

Intuition

Time O(n + m)Space O(m)

The optimal approach uses two pointers to find the leftmost and rightmost indices of characters in t that can be matched in s. This allows us to efficiently calculate the minimum score without generating all subsequences.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create two arrays, leftmost and rightmost, to store the minimum indices of characters in t that can be matched in s from the left and right respectively.
  2. 2Step 2: Use two pointers to fill the leftmost array by iterating through s and t from the left.
  3. 3Step 3: Use two pointers to fill the rightmost array by iterating through s and t from the right.
  4. 4Step 4: Calculate the minimum score using the leftmost and rightmost arrays.
solution.py26 lines
1# Full working Python code
2
3def min_score_subsequence(s, t):
4    n, m = len(s), len(t)
5    leftmost = [-1] * (m + 1)
6    rightmost = [-1] * (m + 1)
7
8    j = 0
9    for i in range(n):
10        if j < m and s[i] == t[j]:
11            leftmost[j] = i
12            j += 1
13
14    j = m - 1
15    for i in range(n - 1, -1, -1):
16        if j >= 0 and s[i] == t[j]:
17            rightmost[j] = i
18            j -= 1
19
20    min_score = float('inf')
21    for i in range(m + 1):
22        if leftmost[i] != -1 and rightmost[i] != -1:
23            min_score = min(min_score, rightmost[i] - leftmost[i] + 1)
24
25    return min_score
26

Complexity note: This complexity is efficient because we only traverse the strings a limited number of times to fill the leftmost and rightmost arrays.

  • 1Understanding subsequences is crucial; they maintain the order of characters.
  • 2Using two pointers can significantly reduce the time complexity by avoiding unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.