Taro Logo

Smallest K-Length Subsequence With Occurrences of a Letter

Hard
Asked by:
Profile picture
5 views
Topics:
StringsGreedy AlgorithmsStacks

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.

Example 1:

Input: s = "leet", k = 3, letter = "e", repetition = 1
Output: "eet"
Explanation: There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:
- "lee" (from "leet")
- "let" (from "leet")
- "let" (from "leet")
- "eet" (from "leet")
The lexicographically smallest subsequence among them is "eet".

Example 2:

example-2
Input: s = "leetcode", k = 4, letter = "e", repetition = 2
Output: "ecde"
Explanation: "ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times.

Example 3:

Input: s = "bb", k = 2, letter = "b", repetition = 2
Output: "bb"
Explanation: "bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times.

Constraints:

  • 1 <= repetition <= k <= s.length <= 5 * 104
  • s consists of lowercase English letters.
  • letter is a lowercase English letter, and appears in s at least repetition times.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the string s, and are we guaranteed that a valid subsequence of length k with at least repetition occurrences of letter always exists?
  2. What is the character set of the string s? Can we assume it only contains lowercase English letters?
  3. If the repetition requirement has already been met, can subsequent instances of the letter still be included in our subsequence if they help make the result lexicographically smaller?
  4. Can the integer k be larger than the length of string s, or is k guaranteed to be less than or equal to s.length()?
  5. When you say 'lexicographically smallest subsequence', does that mean we compare characters using standard ASCII/alphabetical order where 'a' is the smallest?

Brute Force Solution

Approach

To solve this problem using the brute force approach, you need to look at every possible combination of letters that you can make from the original word. After checking all of those combinations, you simply pick the one that is the right length, contains the required number of a specific letter, and comes first in alphabetical order.

Here's how the algorithm would work step-by-step:

  1. Begin by generating every possible smaller word you can make by picking letters from the original word while keeping them in their original order.
  2. Filter through all these generated combinations to keep only the ones that match the target length requirement.
  3. From this smaller group, remove any combinations that do not contain the required number of the specific target letter.
  4. Compare all the remaining valid combinations against each other to see which one comes first in alphabetical order.
  5. Select that first-ranking combination as your final answer.

Code Implementation

import itertools


def smallest_subsequence(source_word, target_length, target_letter, required_count):
    # Generate all subsequences by checking every possible index combination
    all_combinations = []
    for index_combination in itertools.combinations(range(len(source_word)), target_length):
        current_subsequence = "".join(source_word[index] for index in index_combination)
        all_combinations.append(current_subsequence)

    # Filter combinations to only keep those containing enough target letters
    valid_combinations = [
        subsequence for subsequence in all_combinations 
        if subsequence.count(target_letter) >= required_count
    ]

    # Sort valid combinations lexicographically to find the smallest alphabetical option
    valid_combinations.sort()

    return valid_combinations[0]

Big(O) Analysis

Time Complexity
O(2ⁿ) – To generate every possible combination or subsequence from the original word of length n, the algorithm makes a binary choice for each character of either including it or excluding it. This exponential process results in 2ⁿ possible subsequences that must be generated and stored. Filtering, validating the target letter counts, and sorting these subsets takes additional time proportional to the number of combinations. Thus, the total operations approximate 2ⁿ * n, which simplifies to the exponential Big O of 2ⁿ.
Space Complexity
O(2^N * K) – The brute force approach requires generating and storing every possible combination of letters from the original word of length N, resulting in up to 2 to the power of N subsets. Each of these stored combinations takes up to K space for the target length requirement. Additionally, intermediate filtering and comparison steps hold multiple generated subsequences in memory simultaneously. Therefore, the auxiliary space complexity scales exponentially with the input size N.

Optimal Solution

Approach

Instead of checking every single possible combination, the optimal strategy builds the desired sequence step by step using a stack-like mental model. It ensures we keep the smallest possible letters in alphabetical order while guaranteeing we meet the exact count requirement for the special letter and reach the target length.

Here's how the algorithm would work step-by-step:

  1. Look through the text from beginning to end to count how many times the special letter appears in total.
  2. Keep a running collection of chosen letters, removing a previously chosen letter if a smaller alphabetical letter appears later, as long as we still have enough letters left in the text to finish building the sequence.
  3. Check if dropping the last chosen letter would leave us short on either the final target length or the required count of the special letter; if it would, keep it.
  4. If the collection is already at the target length, only accept a new letter if it is smaller than the last one in the collection and we can still afford to lose that last letter without failing our requirements.
  5. If we are getting close to the end of the text and desperately need to secure our remaining required special letters, force-add the special letter immediately.
  6. If we have extra space in our collection but still need more special letters, force-add the special letter to meet the quota.
  7. Stop adding letters once the final target length is reached, making sure any leftover capacity is filled with non-special letters if the special letter quota has already been met.

Code Implementation

class Solution:
    def smallest_subsequence(self, source_text: str, target_length: int, special_letter: str, min_occurrences: int) -> str:
        total_special_count = source_text.count(special_letter)
        selected_characters = []
        
        for index, current_character in enumerate(source_text):
            # Maintain lexicographical order by removing larger elements when possible.
            while selected_characters and selected_characters[-1] > current_character and (len(selected_characters) + len(source_text) - index > target_length) and (selected_characters[-1] != special_letter or total_special_count > min_occurrences):
                if selected_characters.pop() == special_letter:
                    min_occurrences += 1
            
            characters_remaining = len(source_text) - index
            space_available = target_length - len(selected_characters)
            
            if space_available > 0:
                # Force add the special letter if remaining space equals needed occurrences.
                if current_character == special_letter and min_occurrences > 0:
                    selected_characters.append(current_character)
                    min_occurrences -= 1
                elif current_character != special_letter and target_length - len(selected_characters) > min_occurrences:
                    selected_characters.append(current_character)
            
            if current_character == special_letter:
                total_special_count -= 1
        
        return "".join(selected_characters)

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the length of the input string. We iterate through the string a constant number of times to precalculate the total frequency of the special letter. Then, we process each character of the string in a single linear pass, pushing and popping elements from our stack-like collection. Each character is pushed onto and popped from the stack at most once because the inner removal checks only depend on the remaining valid letters. This linear traversal results in approximately 2 * n total operations, which simplifies to Big O of n.
Space Complexity
O(k) – The auxiliary space is driven by the running collection of chosen letters, which acts as a stack holding at most k elements as it builds the final sequence of the target length. Additionally, a few primitive integer counters are used to track occurrences and remaining requirements, consuming constant extra memory. Since k is at most equal to the input size n, the auxiliary space grows linearly with k in the worst-case scenario. Therefore, simplifying to Big O notation yields O(k).

Edge Cases

String length equals k and requires all characters to be the target letter
How to Handle:
The algorithm must greedily include every instance of the letter while filtering out unnecessary characters to match the exact length k.
String contains fewer instances of the letter than the required repetition count
How to Handle:
The problem constraints typically guarantee a valid answer exists, but our logic must ensure we force-include the letter if remaining slots equal remaining required repetitions.
Target letter appears more than enough times but is located late in the string
How to Handle:
A monotonic stack approach combined with a suffix count of the letter ensures we do not greedily pop required letter instances prematurely.
All characters in the string are identical
How to Handle:
The stack will simply accumulate characters up to length k, naturally satisfying the lexicographical and frequency constraints.
Target letter repetition requirement is zero
How to Handle:
The algorithm simplifies to finding the standard lexicographically smallest subsequence of length k without any forced character inclusions.
K is equal to 1 and repetition is 1
How to Handle:
The greedy choice will evaluate the first valid occurrence of the letter or smaller characters depending on availability and constraints.
Maximum length string inputs leading to time limit exceeded
How to Handle:
Using an efficient O(N) monotonic stack with precomputed suffix counts prevents performance bottlenecks on large inputs.
Characters smaller than the target letter appear after we have fulfilled the letter count
How to Handle:
The stack pop condition must strictly verify that removing a character does not drop the total count of the target letter below the required repetition threshold.