VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-a-letter-to-equalize-the-frequency/

⇱ Remove at most K letter to equalize the frequency - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove at most K letter to equalize the frequency

Last Updated : 11 Jun, 2024

Given a string S of length n, consisting of lowercase English letters. The task is to check if it is possible to remove at most K letter from S such that the frequency of every remaining letter is equal.

Examples:

Input: S = "aabbcc", K = 2
Output: True
Explanation: We can remove one 'a' and one 'b' to get "abbcc", where the frequency of each remaining letter is 2

Input: S = "eaabbccd", K = 1
Output: False
Explanation: Removing any one letter won't be enough to make the frequency of every remaining letter equal.

Approach:

The goal is to see if we can remove up to K letters to make all remaining letters in S have the same frequency. To achieve this, we can follow these steps:

  1. Count the frequency of each letter in the string.
  2. Determine the unique frequencies of these counts.
  3. Analyze if adjusting these frequencies by removing up to K letters can make the frequencies equal.

Step-by-Step Approach:

  • Count the frequency of each character in the string S.
  • Record the frequencies in a map or array.
  • Determine the unique frequency values.
  • Check if you can make all frequencies equal by removing at most K letters:
    • If there's only one unique frequency, return True.
    • If there are two unique frequencies, check the conditions under which you can adjust them to become equal by removing up to K letters.
    • If more than two unique frequencies exist, it's not possible to equalize them by removing K letters, return False.

Below is the implementation of the above approach:


Output
Example 1: True
Example 2: False

Time Complexity: O(n + m*logm) Counting frequencies takes O(n). Sorting the frequencies takes O(m*logm) where m is the number of unique characters (at most 26 for lowercase English letters).

Auxiliary Space: O(m) The frequency map and the vector to store frequencies both use O(m) space.


Comment