LeetCode 2716: Minimize String Length Solution
Master LeetCode problem 2716 (Minimize String Length), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2716. Minimize String Length
Problem Explanation
Explanation
To minimize the length of the string, we need to remove characters strategically by choosing the closest occurrences to the left or right of a specific index. We can achieve this by iterating through the string and maintaining a mapping of characters to their indices. We then iterate again through the string, checking for each character the closest occurrence to the left and the right and removing it if necessary.
- Create a map to store the indices of characters.
- Iterate through the string and populate the map.
- Iterate again through the string, for each character:
- Find the closest occurrence to the left and the right from the map.
- Remove the character if a closest occurrence exists.
- Return the length of the modified string.
Time complexity: O(n) where n is the length of the input string s. Space complexity: O(n) for the map.
Solution Code
class Solution {
public int minimizeStringLength(String s) {
Map<Character, Integer> charMap = new HashMap<>();
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
charMap.put(chars[i], i);
}
for (int i = 0; i < chars.length; i++) {
int left = i;
int right = i;
while (left >= 0 && !charMap.containsKey(chars[left])) {
left--;
}
while (right < chars.length && !charMap.containsKey(chars[right])) {
right++;
}
if (left >= 0 && right < chars.length) {
if (i - left < right - i) {
chars[left] = '-';
} else {
chars[right] = '-';
}
} else if (left >= 0) {
chars[left] = '-';
} else if (right < chars.length) {
chars[right] = '-';
}
}
int count = 0;
for (char c : chars) {
if (c != '-') {
count++;
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2716 (Minimize String Length)?
This page provides optimized solutions for LeetCode problem 2716 (Minimize String Length) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2716 (Minimize String Length)?
The time complexity for LeetCode 2716 (Minimize String Length) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2716 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2716 in Java, C++, or Python.