Taro Logo

Filter Characters by Frequency

#1 Most AskedEasy
0 views
Topics:
Strings

You are given a string s consisting of lowercase English letters and an integer k.

Your task is to construct a new string that contains only those characters from s which appear fewer than k times in the entire string. The order of characters in the new string must be the same as their order in s.

Return the resulting string. If no characters qualify, return an empty string.

Note: Every occurrence of a character that occurs fewer than k times is kept.

Example 1:

Input: s = "aadbbcccca", k = 3

Output: "dbb"

Explanation:

Character frequencies in s:

  • 'a' appears 3 times
  • 'd' appears 1 time
  • 'b' appears 2 times
  • 'c' appears 4 times

Only 'd' and 'b' appear fewer than 3 times. Preserving their order, the result is "dbb".

Example 2:

Input: s = "xyz", k = 2

Output: "xyz"

Explanation:

All characters ('x', 'y', 'z') appear exactly once, which is fewer than 2. Thus the whole string is returned.

Constraints:

  • 1 <= s.length <= 100
  • s consists of lowercase English letters.
  • 1 <= k <= s.length

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 character set should we expect in the string? For example, are we dealing only with standard ASCII lowercase English letters, or could it include uppercase letters, digits, whitespace, or Unicode/multibyte characters?
  2. How should the algorithm handle an empty string or a case where no characters meet the minimum frequency threshold $k$? Should it return an empty string?
  3. Can $k$ be less than 1, and if so, how should that be handled?
  4. Does 'original relative order' mean that the remaining characters must appear in the exact sequence they were first encountered in the input string, or should they be grouped by frequency?
  5. How should ties in character frequencies be handled when constructing the final output?

Brute Force Solution

Approach

This problem requires filtering characters in a string based on their total occurrences. Characters that appear strictly fewer than a specified threshold are preserved in their original order. The solution computes character frequencies first and then filters the string accordingly.

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

  1. Import Counter from the collections module to count character frequencies.
  2. Compute the total frequency of each character in the input string.
  3. Initialize an empty list to store characters that satisfy the frequency condition.
  4. Iterate over each character in the input string while checking if its frequency is strictly less than the threshold.
  5. Append qualifying characters to the list to maintain their original relative order.
  6. Join the collected characters into a single string and return the result.

Code Implementation

from collections import Counter

def filter_characters_by_frequency(input_string, threshold):
    # Count the frequency of each character across the input string
    frequency_map = Counter(input_string)
    result_characters = []
    # Iterate through characters and keep those appearing fewer than the threshold
    for current_char in input_string:
        if frequency_map[current_char] < threshold:
            result_characters.append(current_char)
    # Combine the filtered characters into the final string
    return "".join(result_characters)

Big(O) Analysis

Time Complexity
O(N) – Counting character frequencies takes O(N) time where N is the length of the string, and iterating through the string to filter characters also takes O(N) time.
Space Complexity
O(N) – The frequency map stores at most 26 lowercase English letters, which is O(1) space, but the list used to accumulate the output characters takes up to O(N) space.

Optimal Solution

Approach

This problem requires filtering characters from an input string based on their total occurrences. Characters with an overall frequency strictly less than a specified threshold are retained in their original sequence. The solution determines frequencies first and then performs a linear scan to construct the final output.

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

  1. Calculate the frequency of every character present in the input string using a hash map.
  2. Initialize an empty list to collect characters that meet the frequency condition.
  3. Iterate through the original string from left to right to preserve the relative order.
  4. Check if the frequency of the current character is strictly less than the threshold.
  5. Append qualifying characters to the list.
  6. Join the collected characters into a single string and return the result.

Code Implementation

from collections import Counter

def filter_characters_by_frequency(input_string: str, threshold: int) -> str:
    # Count the total occurrences of each character in the string
    frequency_map = Counter(input_string)
    filtered_characters = []
    # Iterate through each character to keep those below the threshold frequency
    for current_char in input_string:
        if frequency_map[current_char] < threshold:
            filtered_characters.append(current_char)
    # Combine the remaining characters into a single string
    return "".join(filtered_characters)

Big(O) Analysis

Time Complexity
O(n) – Counting character frequencies takes O(n) time, where n is the length of the string. A second pass over the string takes O(n) time to filter characters, and joining them takes O(n) time, resulting in linear total time.
Space Complexity
O(n) – The frequency map stores at most 26 lowercase English letters, which is O(1) auxiliary space, while the list storing the filtered characters takes up to O(n) space to hold the output.

Edge Cases

Empty string input
How to Handle:
Return the empty string immediately since no characters meet the frequency threshold.
K is greater than the length of the string
How to Handle:
Return an empty string because no character can possibly appear k times.
K is equal to zero or negative
How to Handle:
Treat all characters as valid since every character appears at least zero or negative times.
All characters appear fewer than k times
How to Handle:
Filter out all characters and return an empty string.
All characters appear at least k times
How to Handle:
Preserve the original string entirely and return it as is.
String contains non-alphanumeric characters, spaces, or unicode symbols
How to Handle:
Count and filter them using their exact character values without special handling.
Extremely long strings reaching maximum memory limits
How to Handle:
Use a linear pass frequency map and a second filtering pass to operate efficiently in O(n) time.
0/7 completed