Ctrl K

Fill the Blanks With the Fewest Repeats

Medium
You are given a string pattern made of lowercase English letters and ? marks. Every ? has to be replaced with some lowercase English letter. The **cost** of the finished string works like this: walk through it from left to right and, for every letter, add how many times that same letter has already appeared to its left. For example, "abab" costs 0 + 0 + 1 + 1 = 2. Replace all the ? marks so that the cost is as small as possible. If several strings reach that minimum, return the lexicographically smallest one.
Example 1
pattern='b??b' → 'bacb'

The two bs are already there, so one repeated pair is unavoidable. The cheapest choice for the question marks is letters not used yet, a and c. That gives "bacb" with cost 1, and it is the alphabetically smallest of all cost-1 options.

Example 2
pattern='?zz?' → 'azzb'

Letters a and b are still unused. The smaller one, a, goes to the earlier position, because "azzb" is smaller than "bzza".

Example 3
pattern='kite' → 'kite'

There are no question marks, so the string comes back unchanged.

Constraints
  • 1 ≤ len(pattern) ≤ 10⁵
  • pattern[i] is a lowercase English letter or ?
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNo Twin Letters Side by Side MediumEqual Letters Kept Apart HardCharacters Grouped by Count MediumJobs With a Cooldown MediumMost Searched Words Medium
loading Python…
Input
pattern='b??b'
Expected
'bacb'

Run checks the first 3 tests in your browser. Submit checks all 41 tests on the server, hidden ones included.