Replace Question Marks in String to Minimize Its Value - Problem
Replace Question Marks to Minimize String Value
You are given a string
How is the value calculated?
For any string, the value is the sum of costs for each position. The cost at position
Example: For string
• Position 0 ('a'): cost = 0 (no previous 'a')
• Position 1 ('a'): cost = 1 (one previous 'a')
• Position 2 ('b'): cost = 0 (no previous 'b')
• Total value = 0 + 1 + 0 = 1
Goal: Replace all
You are given a string
s containing lowercase letters and question marks (?). Your task is to replace all question marks with lowercase letters to minimize the value of the resulting string.How is the value calculated?
For any string, the value is the sum of costs for each position. The cost at position
i equals the number of times the character at position i has appeared before position i.Example: For string
"aab":• Position 0 ('a'): cost = 0 (no previous 'a')
• Position 1 ('a'): cost = 1 (one previous 'a')
• Position 2 ('b'): cost = 0 (no previous 'b')
• Total value = 0 + 1 + 0 = 1
Goal: Replace all
? characters to minimize the total value. If multiple solutions exist with the same minimum value, return the lexicographically smallest one. Input & Output
example_1.py — Basic Replacement
$
Input:
s = "???"
Output: "abc"
›
Output:
"abc"
💡 Note:
Replace all question marks with the lexicographically smallest characters. Since all positions are empty, we choose 'a', 'b', 'c' in order to minimize the total value: 0 + 0 + 0 = 0.
example_2.py — Mixed Characters
$
Input:
s = "a?b?"
Output: "abac"
›
Output:
"abac"
💡 Note:
Position 0: 'a' (given), Position 1: choose 'b' (freq 0), Position 2: 'b' (given), Position 3: choose 'a' (freq 1) vs 'c' (freq 0) → choose 'c'. Final value: 0 + 0 + 1 + 0 = 1.
example_3.py — All Same Character
$
Input:
s = "aaa"
Output: "aaa"
›
Output:
"aaa"
💡 Note:
No question marks to replace. The value is 0 + 1 + 2 = 3. This is already the minimum possible for this input.
Constraints
- 1 ≤ s.length ≤ 105
- s[i] is either a lowercase English letter or '?'
- At least one character in s is '?'
Visualization
Tap to expand
Understanding the Visualization
1
Track Popularity
Keep count of how many times each book (character) has been checked out
2
Process Customers
For each customer (position), either record their specific choice or recommend optimally
3
Minimize Costs
When recommending (?), always choose the least popular book to minimize checkout fee
4
Update Records
After each checkout, increment that book's popularity count for future decisions
Key Takeaway
🎯 Key Insight: The greedy approach works because each character's cost depends only on its previous frequency. By always choosing the least frequent character, we minimize the immediate cost without affecting future optimal choices.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code