Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string.
Examples:
Input: str = “xyyz”
Output: Yes
We can remove character ’y’ from above
string to make the frequency of each
character same.
Input: str = “xyyzz”
Output: Yes
We can remove character ‘x’ from above
string to make the frequency of each
character same.
Input: str = “xxxxyyzz”
Output: No
It is not possible to make frequency of
each character same just by removing at
most one character from above string.
Approach: The problem can be solved using the concept of hashing. The main thing to observe in this problem is that the position of characters does not matter here so we will count the frequency of characters, if all of them are the same then we are done and there is no need to remove any character to make frequency of characters same Otherwise we can iterate over all characters one by one and decrease their frequency by one, if all frequencies become same then we will flag that it is possible to make character frequency same by at most one removal and if frequencies don’t match then we will increase that frequency again and loop for other characters.
Below is a dry run of the above approach:

Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define M 26
int getIdx( char ch)
{
return (ch - 'a' );
}
bool allSame( int freq[], int N)
{
int same;
int i;
for (i = 0; i < N; i++) {
if (freq[i] > 0) {
same = freq[i];
break ;
}
}
for ( int j = i + 1; j < N; j++)
if (freq[j] > 0 && freq[j] != same)
return false ;
return true ;
}
bool possibleSameCharFreqByOneRemoval(string str)
{
int l = str.length();
int freq[M] = { 0 };
for ( int i = 0; i < l; i++)
freq[getIdx(str[i])]++;
if (allSame(freq, M))
return true ;
for ( char c = 'a' ; c <= 'z' ; c++) {
int i = getIdx(c);
if (freq[i] > 0) {
freq[i]--;
if (allSame(freq, M))
return true ;
freq[i]++;
}
}
return false ;
}
int main()
{
string str = "xyyzz" ;
if (possibleSameCharFreqByOneRemoval(str))
cout << "Yes" ;
else
cout << "No" ;
}
|
Java
public class GFG {
static final int M = 26 ;
static int getIdx( char ch)
{
return (ch - 'a' );
}
static boolean allSame( int freq[], int N)
{
int same = 0 ;
int i;
for (i = 0 ; i < N; i++) {
if (freq[i] > 0 ) {
same = freq[i];
break ;
}
}
for ( int j = i + 1 ; j < N; j++)
if (freq[j] > 0 && freq[j] != same)
return false ;
return true ;
}
static boolean possibleSameCharFreqByOneRemoval(String str)
{
int l = str.length();
int [] freq = new int [M];
for ( int i = 0 ; i < l; i++)
freq[getIdx(str.charAt(i))]++;
if (allSame(freq, M))
return true ;
for ( char c = 'a' ; c <= 'z' ; c++) {
int i = getIdx(c);
if (freq[i] > 0 ) {
freq[i]--;
if (allSame(freq, M))
return true ;
freq[i]++;
}
}
return false ;
}
public static void main(String args[])
{
String str = "xyyzz" ;
if (possibleSameCharFreqByOneRemoval(str))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
M = 26
def getIdx(ch):
return ( ord (ch) - ord ( 'a' ))
def allSame(freq, N):
for i in range ( 0 , N):
if (freq[i] > 0 ):
same = freq[i]
break
for j in range (i + 1 , N):
if (freq[j] > 0 and freq[j] ! = same):
return False
return True
def possibleSameCharFreqByOneRemoval(str1):
l = len (str1)
freq = [ 0 ] * M
for i in range ( 0 , l):
freq[getIdx(str1[i])] + = 1
if (allSame(freq, M)):
return True
for i in range ( 0 , 26 ):
if (freq[i] > 0 ):
freq[i] - = 1
if (allSame(freq, M)):
return True
freq[i] + = 1
return False
if __name__ = = "__main__" :
str1 = "xyyzz"
if (possibleSameCharFreqByOneRemoval(str1)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static int M = 26;
static int getIdx( char ch)
{
return (ch - 'a' );
}
static bool allSame( int [] freq,
int N)
{
int same = 0;
int i;
for (i = 0; i < N; i++) {
if (freq[i] > 0) {
same = freq[i];
break ;
}
}
for ( int j = i + 1; j < N; j++)
if (freq[j] > 0 && freq[j] != same)
return false ;
return true ;
}
static bool possibleSameCharFreqByOneRemoval( string str)
{
int l = str.Length;
int [] freq = new int [M];
for ( int i = 0; i < l; i++)
freq[getIdx(str[i])]++;
if (allSame(freq, M))
return true ;
for ( char c = 'a' ; c <= 'z' ; c++) {
int i = getIdx(c);
if (freq[i] > 0) {
freq[i]--;
if (allSame(freq, M))
return true ;
freq[i]++;
}
}
return false ;
}
public static void Main()
{
string str = "xyyzz" ;
if (possibleSameCharFreqByOneRemoval(str))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
PHP
<?php
$M = 26;
function getIdx( $ch )
{
return ( $ch - 'a' );
}
function allSame(& $freq , $N )
{
for ( $i = 0; $i < $N ; $i ++)
{
if ( $freq [ $i ] > 0)
{
$same = $freq [ $i ];
break ;
}
}
for ( $j = $i + 1; $j < $N ; $j ++)
if ( $freq [ $j ] > 0 &&
$freq [ $j ] != $same )
return false;
return true;
}
function possibleSameCharFreqByOneRemoval( $str )
{
global $M ;
$l = strlen ( $str );
$freq = array_fill (0, $M , NULL);
for ( $i = 0; $i < $l ; $i ++)
$freq [getIdx( $str [ $i ])]++;
if (allSame( $freq , $M ))
return true;
for ( $c = 'a' ; $c <= 'z' ; $c ++)
{
$i = getIdx( $c );
if ( $freq [ $i ] > 0)
{
$freq [ $i ]--;
if (allSame( $freq , $M ))
return true;
$freq [ $i ]++;
}
}
return false;
}
$str = "xyyzz" ;
if (possibleSameCharFreqByOneRemoval( $str ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
let M = 26;
function getIdx(ch)
{
return (ch - 'a' );
}
function allSame(freq, N)
{
let same = 0;
let i;
for (i = 0; i < N; i++)
{
if (freq[i] > 0)
{
same = freq[i];
break ;
}
}
for (let j = i + 1; j < N; j++)
if (freq[j] > 0 && freq[j] != same)
return false ;
return true ;
}
function possibleSameCharFreqByOneRemoval(str)
{
let l = str.length;
let freq = new Array(M);
for (let i = 0; i < M; i++)
{
freq[i] = 0;
}
for (let i = 0; i < l; i++)
freq[getIdx(str[i])]++;
if (allSame(freq, M))
return true ;
for (let c = 'a' ; c <= 'z' ; c++)
{
let i = getIdx(c);
if (freq[i] > 0)
{
freq[i]--;
if (allSame(freq, M))
return true ;
freq[i]++;
}
}
return false ;
}
let str = "xyyzz" ;
if (possibleSameCharFreqByOneRemoval(str))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n) assuming alphabet size is constant.
Auxiliary Space: O(1)
Alternate way to solve this problem using Collections framework
In this approach we are going to use Collection class to solve the given problem.
Steps:
1. First we will take 2 hashmap. One will used to store character and its count and another will stored the count of occurrence of character and number to character which having same count.
2. After this if 2nd hashmap size is 1 that means character frequency is one so we simply return true.
3. Now we will declare 2 arraylist to store key in one arraylist and values in another list.
4. Now we will check if it is possible to make frequency of character by one removal or not. If yes then return true else return false.
C++
#include <bits/stdc++.h>
using namespace std;
bool sameFreq(string s)
{
map< char , int > h;
map< int , int > a;
for ( int i = 0; i < s.length(); i++)
{
h[s[i]]++;
}
for ( auto map : h) {
a[map.second]++;
}
if (a.size() == 1) {
return true ;
}
else if (a.size() == 2) {
vector< int > list;
vector< int > l;
for ( auto entry : a) {
int key = entry.first;
int value = entry.second;
list.push_back(key);
l.push_back(value);
}
if ((list[1] == 1 && l[1] == 1)
|| (list[0] == 1 && l[0] == 1)) {
return true ;
}
else if ( abs (list[1] - list[0]) == 1) {
return true ;
}
else {
return false ;
}
}
else {
return false ;
}
}
int main()
{
string str = "xxxyyz" ;
if (sameFreq(str)) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
return 0;
}
|
Java
import java.util.*;
public class HelloWorld {
static public boolean sameFreq(String s) {
HashMap<Character, Integer> h = new HashMap<>();
HashMap<Integer, Integer> a = new HashMap<>();
for ( int i = 0 ; i<s.length(); i++)
{
h.put(s.charAt(i), h.getOrDefault(s.charAt(i), 0 )+ 1 );
}
for (Map.Entry<Character, Integer> map : h.entrySet()) {
a.put(map.getValue(), a.getOrDefault(map.getValue(), 0 )+ 1 );
}
if (a.size() == 1 )
{
return true ;
}
if (a.size() == 2 )
{
ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> l = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : a.entrySet()) {
Integer key = entry.getKey();
Integer value = entry.getValue();
list.add(key);
l.add(value);
}
if ((list.get( 1 ) == 1 && l.get( 1 ) == 1 ) || (list.get( 0 ) == 1 && l.get( 0 ) == 1 )) {
return true ;
}
else if (Math.abs(list.get( 1 ) - list.get( 0 )) == 1 ) {
return true ;
}
else
{
return false ;
}
}
else
{
return false ;
}
}
public static void main(String[] args)
{
String str= "xxxyyz" ;
if (sameFreq(str)){
System.out.println( "YES" );
} else {
System.out.println( "NO" );
}
}
}
|
Python3
def sameFreq(s):
h = {}
a = {}
for i in s:
h[i] = h.get(i, 0 ) + 1
for key, value in h.items():
a[value] = a.get(value, 0 ) + 1
if len (a) = = 1 :
return True
elif len (a) = = 2 :
l = []
list = []
for key, value in a.items():
list .append(key)
l.append(value)
if ( list [ 1 ] = = 1 and l[ 1 ] = = 1 ) or ( list [ 0 ] = = 1 and l[ 0 ] = = 1 ):
return True
elif abs ( list [ 1 ] - list [ 0 ]) = = 1 :
return True
else :
return False
else :
return False
str = "xxxyyz"
if sameFreq( str ):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
using System.Collections.Generic;
class Program {
static bool SameFreq( string s)
{
Dictionary< char , int > h
= new Dictionary< char , int >();
Dictionary< int , int > a = new Dictionary< int , int >();
foreach ( char c in s)
{
if (h.ContainsKey(c)) {
h++;
}
else {
h.Add(c, 1);
}
}
foreach (KeyValuePair< char , int > kvp in h)
{
if (a.ContainsKey(kvp.Value)) {
a[kvp.Value]++;
}
else {
a.Add(kvp.Value, 1);
}
}
if (a.Count == 1) {
return true ;
}
else if (a.Count == 2) {
List< int > list = new List< int >();
List< int > l = new List< int >();
foreach (KeyValuePair< int , int > kvp in a)
{
int key = kvp.Key;
int value = kvp.Value;
list.Add(key);
l.Add(value);
}
if ((list[1] == 1 && l[1] == 1)
|| (list[0] == 1 && l[0] == 1)) {
return true ;
}
else if (Math.Abs(list[1] - list[0]) == 1) {
return true ;
}
else {
return false ;
}
}
else {
return false ;
}
}
static void Main( string [] args)
{
string str = "xxxyyz" ;
if (SameFreq(str)) {
Console.WriteLine( "YES" );
}
else {
Console.WriteLine( "NO" );
}
}
}
|
Javascript
function sameFreq(s) {
let h = new Map();
let a = new Map();
for (let i = 0; i < s.length; i++) {
h.set(s[i], (h.get(s[i]) || 0) + 1);
}
for (let [key, value] of h) {
a.set(value, (a.get(value) || 0) + 1);
}
if (a.size === 1) {
return true ;
}
else if (a.size === 2) {
let list = [];
let l = [];
for (let [key, value] of a) {
list.push(key);
l.push(value);
}
if ((list[1] === 1 && l[1] === 1)
|| (list[0] === 1 && l[0] === 1)) {
return true ;
}
else if (Math.abs(list[1] - list[0]) === 1) {
return true ;
}
else {
return false ;
}
}
else {
return false ;
}
}
let str = "xxxyyz" ;
if (sameFreq(str)) {
console.log( "YES" );
}
else {
console.log( "NO" );
}
|
Time Complexity: O(n), where n is the size of the string
Auxiliary Space: O(n), extra space used for hashmap
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
05 Apr, 2023
Like Article
Save Article