1717. Quota-Bound Subsequence

Hard7.5 points estimatedMonotonic StackGreedyStringStack

A radio station is assembling a playlist code from the genre letters in the string s, one letter per song of the day. It must keep exactly k songs, preserving their original order (a subsequence of s of length exactly k), and the chosen subsequence has to contain the genre letter at least rep times. Among all such subsequences return the lexicographically smallest one, or the empty string if none exists. The string has 1 to 100000 lowercase letters, 1 <= k <= s.length, letter is a lowercase letter and 1 <= rep <= k. Aim for O(n) time and O(n) space: use a monotonic stack that pops a larger top only while enough characters remain to reach length k and enough copies of letter remain to meet the quota.

Example 1

Input:
s = "bacbab"k = 3letter = "b"rep = 2
Output:
"abb"
Explanation:

Choosing the a at index 1 and the b at indices 3 and 5 gives "abb", the smallest length-3 subsequence with at least two b letters.

Example 2

Input:
s = "abc"k = 2letter = "z"rep = 1
Output:
""
Explanation:

The string has no z, so the quota cannot be met and the answer is empty.

Example 3

Input:
s = "zyxw"k = 2letter = "z"rep = 1
Output:
"zw"
Explanation:

The z at index 0 must be kept, and the smallest partner after it is w, giving "zw".

Constraints

1 ≤ k ≤ s.length ≤ 105

s consists of lowercase letters; letter is a lowercase letter

1 ≤ rep ≤ k

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…