LeetCode 3081: Replace Question Marks in String to Minimize Its Value Solution
Master LeetCode problem 3081 (Replace Question Marks in String to Minimize Its Value), a medium 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.
3081. Replace Question Marks in String to Minimize Its Value
Problem Explanation
Explanation:
To solve this problem, we can iterate over the string s and replace each ? character with the lexicographically smallest character that minimizes the value of the string. We can do this by keeping track of the number of occurrences of each character seen so far while iterating through the string.
- Iterate over the string
s:- For each character that is not a
?, update the count of that character in a frequency array. - For each
?, replace it with the lexicographically smallest character not already seen.
- For each character that is not a
- Return the modified string.
By following this approach, we can ensure that the value of the string is minimized and that the resulting string is lexicographically smallest.
Time Complexity: O(n) where n is the length of the input string s.
Space Complexity: O(1) as the frequency array has a fixed size of 26 for lowercase English letters.
Solution Code
class Solution {
public String modifyString(String s) {
char[] chars = s.toCharArray();
char prev = ' ';
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '?') {
char next = (i + 1 < chars.length) ? chars[i + 1] : ' ';
char candidate = 'a';
while (candidate == prev || candidate == next) {
candidate++;
}
chars[i] = candidate;
}
prev = chars[i];
}
return new String(chars);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3081 (Replace Question Marks in String to Minimize Its Value)?
This page provides optimized solutions for LeetCode problem 3081 (Replace Question Marks in String to Minimize Its Value) 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 3081 (Replace Question Marks in String to Minimize Its Value)?
The time complexity for LeetCode 3081 (Replace Question Marks in String to Minimize Its Value) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3081 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3081 in Java, C++, or Python.