Smallest K-Length Subsequence With Occurrences of a Letter - Problem
You are given a string s, an integer k, a letter letter, and an integer repetition.
Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input & Output
Example 1 — Basic Case
$
Input:
s = "leetcode", k = 4, letter = "e", repetition = 2
›
Output:
"eetc"
💡 Note:
We need a subsequence of length 4 with at least 2 'e's. "eetc" is lexicographically smallest among valid options like "eetc", "eeto", "eeco", etc.
Example 2 — Minimum Repetition
$
Input:
s = "leetcode", k = 4, letter = "e", repetition = 1
›
Output:
"ecod"
💡 Note:
With only 1 'e' required, we can pick the lexicographically smallest: 'e' from position 1, then 'c', 'o', 'd'.
Example 3 — All Required Letters
$
Input:
s = "aaab", k = 3, letter = "a", repetition = 3
›
Output:
"aaa"
💡 Note:
We need exactly 3 'a's in our subsequence of length 3, so we take all three 'a's.
Constraints
- 1 ≤ s.length ≤ 5 × 104
- 1 ≤ k ≤ s.length
- 1 ≤ repetition ≤ k
- letter is a lowercase English letter
- s contains at least repetition occurrences of letter
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s, length k, target letter, minimum repetitions
2
Process
Use monotonic stack to build lexicographically smallest valid subsequence
3
Output
Subsequence of length k with required letter occurrences
Key Takeaway
🎯 Key Insight: Use a monotonic stack to greedily build the lexicographically smallest subsequence while tracking remaining target letters to ensure constraints can be met
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code