Leetcode 3081: Replace Question Marks in String to Minimize Its Value

grid47
grid47
Exploring patterns and algorithms
Jan 3, 2024 6 min read

You are given a string s consisting of lowercase English letters and question marks (?). Your task is to replace all occurrences of ? with any lowercase English letter in such a way that the total cost of the resulting string is minimized. The cost of a string is the sum of how many times each character has appeared before its current position. If there are multiple solutions with the same minimal cost, return the lexicographically smallest one.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `s` of length `n`, where `1 <= n <= 10^5`, and each character is either a lowercase English letter or `?`.
Example: s = "a?a?"
Constraints:
• 1 <= s.length <= 10^5
• s[i] is either a lowercase English letter or '?'
Output: Return a string where all occurrences of '?' are replaced with lowercase English letters in a way that minimizes the total cost. If there are multiple strings with the same minimal cost, return the lexicographically smallest one.
Example: Output: "abac"
Constraints:
Goal: Minimize the cost of the resulting string by replacing '?' characters.
Steps:
• Iterate over the string and maintain a frequency count of the letters already seen.
• For each '?', select the smallest letter that has appeared the least number of times so far.
• Replace '?' with this letter and update the frequency count.
Goal: The string `s` must have a length between 1 and 10^5 and contain only lowercase English letters or '?'.
Steps:
• 1 <= s.length <= 10^5
• Each character in `s` is either a lowercase English letter or '?'
Assumptions:
• The string can be large, so the solution must be efficient.
• The string only contains lowercase English letters or '?' characters.
Input: s = "a?a?"
Explanation: In this case, replacing the '?' with 'b' and 'c' results in the string 'abac', which has a minimal cost of 1.

Input: s = "???"
Explanation: Replacing the '?' with 'a', 'b', and 'c' results in the string 'abc', which has a minimal cost of 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus