Replace Question Marks in String to Minimize Its Value - Problem

You are given a string s. Each character s[i] is either a lowercase English letter or '?'.

For a string t having length m containing only lowercase English letters, we define the function cost(i) for an index i as the number of characters equal to t[i] that appeared before it, i.e. in the range [0, i - 1].

The value of t is the sum of cost(i) for all indices i.

For example, for the string t = "aab":

  • cost(0) = 0 (no 'a' before index 0)
  • cost(1) = 1 (one 'a' before index 1)
  • cost(2) = 0 (no 'b' before index 2)

Hence, the value of "aab" is 0 + 1 + 0 = 1.

Your task is to replace all occurrences of '?' in s with any lowercase English letter so that the value of s is minimized.

Return a string denoting the modified string with replaced occurrences of '?'. If there are multiple strings resulting in the minimum value, return the lexicographically smallest one.

Input & Output

Example 1 — Basic Case
$ Input: s = "?ab?"
Output: "aaba"
💡 Note: Replace first '?' with 'a' (min freq), second '?' with 'a' (still min among remaining). Result has value: cost(0)=0 + cost(1)=1 + cost(2)=0 + cost(3)=2 = 3
Example 2 — All Question Marks
$ Input: s = "???"
Output: "abc"
💡 Note: Greedily pick 'a', then 'b', then 'c' to minimize value. Each character appears for first time so total value = 0
Example 3 — Mixed Pattern
$ Input: s = "a?a?"
Output: "abac"
💡 Note: First '?' becomes 'b' (min freq), second '?' becomes 'c' (min freq). Value = 0+0+1+0 = 1

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is either a lowercase English letter or '?'

Visualization

Tap to expand
Replace Question Marks: "a?b?" → Minimize Total Costa?b?Original Stringcost = 0replacecost = 0replaceacbdOptimal Result: "acbd"cost = 0cost = 0cost = 0cost = 0Greedy Strategy1. Track frequency of each letter2. For each '?', pick letter with minimum current frequency3. Increment frequency counterResult: Total Value = 0🎯 Key Insight: Always choose the least frequent letter to minimize future costs
Understanding the Visualization
1
Input Analysis
String with '?' characters to replace
2
Cost Calculation
Each character's cost = count of same chars before it
3
Greedy Strategy
Replace each '?' with minimum frequency letter
Key Takeaway
🎯 Key Insight: Greedy approach works because choosing the least frequent letter at each step minimizes the total cost function
Asked in
Google 35 Microsoft 28 Amazon 22 Meta 18
28.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen