2565. Subsequence With the Minimum Score
Explanation
To solve this problem, we can iterate through string s
and keep track of the position of characters in string t
that we encounter in s
. We can then calculate the score based on the positions of the characters in t
that we have found in s
. The minimum score would be the difference between the maximum and minimum positions of the characters in t
in s
.
Algorithm
- Create a map to store the positions of characters in string
t
. - Iterate through string
s
and update the map with the positions of characters int
found ins
. - Calculate the minimum score as the difference between the maximum and minimum positions of characters in
t
ins
.
Time Complexity
The time complexity of this solution is O(n), where n is the length of string s
or t
.
Space Complexity
The space complexity of this solution is O(n), where n is the length of string t
.
class Solution {
public int minScore(String s, String t) {
Map<Character, List<Integer>> positions = new HashMap<>();
for (int i = 0; i < t.length(); i++) {
positions.computeIfAbsent(t.charAt(i), k -> new ArrayList<>()).add(i);
}
int minScore = Integer.MAX_VALUE;
int left = -1, right = -1;
for (char c : s.toCharArray()) {
if (positions.containsKey(c)) {
for (int pos : positions.get(c)) {
if (pos > right) {
right = pos;
}
if (left == -1 || pos < left) {
left = pos;
}
}
}
if (left != -1 && right != -1) {
minScore = Math.min(minScore, right - left + 1);
}
}
return minScore == Integer.MAX_VALUE ? 0 : minScore;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.