Ctrl K

Smallest Pick With a Required Letter

Hard
You get a string text, an integer length, a letter letter and an integer times. Pick exactly length characters from text while keeping their order (a subsequence), such that letter appears among them at least times times. Of all such subsequences, return the lexicographically smallest one, the one that would come first in a dictionary. It is guaranteed that letter occurs in text at least times times, so an answer always exists.
Example 1
text="banana", length=3, letter="n", times=2 → 'ann'

Two of the three letters must be n, and the third should be as small as possible: an a before two ns gives ann.

Example 2
text="zebra", length=2, letter="z", times=1 → 'za'

The z is mandatory and sits at the very start, so it comes first. After it we take the smallest remaining letter, a.

Example 3
text="cabbac", length=4, letter="c", times=2 → 'caac'
Constraints
  • 1 ≤ times ≤ length ≤ len(text) ≤ 5 · 10⁴
  • text consists of lowercase English letters
  • letter is a lowercase English letter that occurs in text at least times times
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Letter Once MediumErase Digits for the Smallest Number MediumOne Bead of Each Color MediumLargest Number From Two Rows HardSorting Batches With Repeats Hard
loading Python…
Input
text="banana", length=3, letter="n", times=2
Expected
'ann'

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