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
.
Examples
Example 1:
$$ \begin{array}{cccc} l & \colorbox{green}{e} & \colorbox{green}{e} & \colorbox{green}{t} \\ \end{array} $$
|
|
Example 2:
$$ \begin{array}{cccccccc} l & e & \colorbox{green}{e} & t & \colorbox{green}{c} & o & \colorbox{green}{d} & \colorbox{green}{e} \\ \end{array} $$
|
|
Example 3: $$ \begin{array}{cc} \colorbox{green}{b} & \colorbox{green}{b} \\ \end{array} $$
|
|
Solution
Method 1 - Using Monotonic Increasing stack
We can use monotonically increasing stack to maintain elements in increasing order in the stack to ensure the smallest lexicographical sequence is formed.
- While iterating through the string, if the current character is smaller than the character at the top of the stack and it is possible to maintain the length of the subsequence (
k
) and required occurrences of theletter
, we pop the top of the stack. - This way, the characters left in the stack are in increasing order, ensuring the sequence remains lexicographically smallest.
Here is the approach:
- Use Monotonic Stack:
- Traverse the string
s
and use a stack to build the resulting subsequence while maintaining the lexicographical order. - Ensure that the resulting subsequence satisfies the constraints:
- Length should be
k
. - It should contain
letter
at leastrepetition
times.
- Length should be
- Traverse the string
- Keep track of necessary elements:
- Use counters to keep track of the remaining necessary occurrences of
letter
.
- Use counters to keep track of the remaining necessary occurrences of
- Greedily build the stack:
- If the current character can replace the top of the stack to form a smaller lexicographical order while maintaining the constraints, do so.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, as the algorithm processes each character in the string once and performs operations on the stack. - 🧺 Space complexity:
O(k)
, due to storing up to k characters in the stack.