#2030
Smallest K-Length Subsequence With Occurrences of a Letter
HardStringStackGreedyMonotonic StackStackGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a stack to build the desired subsequence while ensuring that we maintain the lexicographical order and the required number of occurrences of the specified letter.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a stack to build the result and count the occurrences of the letter in the string.
- 2Step 2: Iterate through each character in the string s.
- 3Step 3: For each character, decide whether to push it onto the stack or pop from the stack based on the current size, remaining characters, and required occurrences of the letter.
- 4Step 4: Ensure that the stack contains the required letter at least 'repetition' times by the end of the iteration.
- 5Step 5: Construct the final result from the stack.
solution.py15 lines
1def smallestKLengthSubsequence(s, k, letter, repetition):
2 stack = []
3 letter_count = s.count(letter)
4 for i, char in enumerate(s):
5 while (stack and stack[-1] > char and
6 len(stack) + len(s) - i > k and
7 (stack[-1] != letter or letter_count > repetition)):
8 stack.pop()
9 if len(stack) < k:
10 if char == letter:
11 stack.append(char)
12 letter_count -= 1
13 elif k - len(stack) > repetition:
14 stack.append(char)
15 return ''.join(stack[:k])ℹ
Complexity note: The complexity is O(n) because we traverse the string once and use a stack to maintain the necessary characters.
- 1Using a stack helps maintain the order of characters while allowing for efficient popping of larger characters.
- 2Counting occurrences of the required letter upfront allows for better decision-making during the stack operations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.