VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-string-has-all-characters-with-same-frequency-with-one-variation-allowed/

⇱ Check equal frequency of distinct characters in string with 1 or 0 removals - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check equal frequency of distinct characters in string with 1 or 0 removals

Last Updated : 23 Jul, 2025

Given a string S having lowercase alphabets, the task is to check if all distinct characters in S occurs same number of times by removing 1 or 0 characters from it.

Examples : 

Input : string str = "abbca"
Output : Yes
Explanation: We can make it valid by removing "c"

Input : string str = "aabbcd"
Output : No
Explanation: We need to remove at least two characters to make it valid.

Input : string str = "abbccd"
Output : No
Explanation: We are allowed to traverse string only once. 

Check equal frequency of distinct characters in string with 1 or 0 removals by Frequency counting:

Use a frequency array that stores frequencies of all characters. Once we have frequencies of all characters in an array, we check if count of total different and non-zero values are not more than 2. Also, one of the counts of two allowed different frequencies must be less than or equal to 2.

Below is the implementation of the above approach:


Output
YES

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1), no other extra space is required, so it is a constant.

Uses a hashmap to count character frequencies and verifies that there are at most two distinct characters with different frequencies.

Below is the implementation.  


Output
true

TimeComplexity: O(N), where N is the length of the given string.
AuxiliarySpace: O(N)

Comment
Article Tags:
Article Tags: