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:
C++
#include <bits/stdc++.h>
using namespace std;
const int CHARS = 26;
bool isValidString(string str)
{
int freq[CHARS] = { 0 };
for ( int i = 0; i < str.length(); i++)
freq[str[i] - 'a' ]++;
int i, freq1 = 0, count_freq1 = 0;
for (i = 0; i < CHARS; i++) {
if (freq[i] != 0) {
freq1 = freq[i];
count_freq1 = 1;
break ;
}
}
int j, freq2 = 0, count_freq2 = 0;
for (j = i + 1; j < CHARS; j++) {
if (freq[j] != 0) {
if (freq[j] == freq1)
count_freq1++;
else {
count_freq2 = 1;
freq2 = freq[j];
break ;
}
}
}
for ( int k = j + 1; k < CHARS; k++) {
if (freq[k] != 0) {
if (freq[k] == freq1)
count_freq1++;
if (freq[k] == freq2)
count_freq2++;
else
return false ;
}
if (count_freq1 > 1 && count_freq2 > 1)
return false ;
}
return true ;
}
int main()
{
char str[] = "abcbc" ;
if (isValidString(str))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
|
C
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
const int CHARS = 26;
bool isValidString( char str[])
{
int freq[CHARS];
for ( int i = 0; i < CHARS; i++)
freq[i] = 0;
for ( int i = 0; i < strlen (str); i++)
freq[str[i] - 'a' ]++;
int i, freq1 = 0, count_freq1 = 0;
for (i = 0; i < CHARS; i++) {
if (freq[i] != 0) {
freq1 = freq[i];
count_freq1 = 1;
break ;
}
}
int j, freq2 = 0, count_freq2 = 0;
for (j = i + 1; j < CHARS; j++) {
if (freq[j] != 0) {
if (freq[j] == freq1)
count_freq1++;
else {
count_freq2 = 1;
freq2 = freq[j];
break ;
}
}
}
for ( int k = j + 1; k < CHARS; k++) {
if (freq[k] != 0) {
if (freq[k] == freq1)
count_freq1++;
if (freq[k] == freq2)
count_freq2++;
else
return false ;
}
if (count_freq1 > 1 && count_freq2 > 1)
return false ;
}
return true ;
}
int main()
{
char str[] = "abcbc" ;
if (isValidString(str))
printf ( "YES\n" );
else
printf ( "NO\n" );
return 0;
}
|
Java
public class GFG {
static int CHARS = 26 ;
static boolean isValidString(String str)
{
int freq[] = new int [CHARS];
for ( int i = 0 ; i < str.length(); i++) {
freq[str.charAt(i) - 'a' ]++;
}
int i, freq1 = 0 , count_freq1 = 0 ;
for (i = 0 ; i < CHARS; i++) {
if (freq[i] != 0 ) {
freq1 = freq[i];
count_freq1 = 1 ;
break ;
}
}
int j, freq2 = 0 , count_freq2 = 0 ;
for (j = i + 1 ; j < CHARS; j++) {
if (freq[j] != 0 ) {
if (freq[j] == freq1) {
count_freq1++;
}
else {
count_freq2 = 1 ;
freq2 = freq[j];
break ;
}
}
}
for ( int k = j + 1 ; k < CHARS; k++) {
if (freq[k] != 0 ) {
if (freq[k] == freq1) {
count_freq1++;
}
if (freq[k] == freq2) {
count_freq2++;
}
else
{
return false ;
}
}
if (count_freq1 > 1 && count_freq2 > 1 ) {
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
String str = "abcbc" ;
if (isValidString(str)) {
System.out.println( "YES" );
}
else {
System.out.println( "NO" );
}
}
}
|
Python3
CHARS = 26
def isValidString( str ):
freq = [ 0 ] * CHARS
for i in range ( len ( str )):
freq[ ord ( str [i]) - ord ( 'a' )] + = 1
freq1 = 0
count_freq1 = 0
for i in range (CHARS):
if (freq[i] ! = 0 ):
freq1 = freq[i]
count_freq1 = 1
break
freq2 = 0
count_freq2 = 0
for j in range (i + 1 ,CHARS):
if (freq[j] ! = 0 ):
if (freq[j] = = freq1):
count_freq1 + = 1
else :
count_freq2 = 1
freq2 = freq[j]
break
for k in range (j + 1 ,CHARS):
if (freq[k] ! = 0 ):
if (freq[k] = = freq1):
count_freq1 + = 1
if (freq[k] = = freq2):
count_freq2 + = 1
else :
return False
if (count_freq1 > 1 and count_freq2 > 1 ):
return False
return True
if __name__ = = "__main__" :
str = "abcbc"
if (isValidString( str )):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
public class GFG {
static int CHARS = 26;
static bool isValidString(String str) {
int []freq = new int [CHARS];
int i=0;
for ( i= 0; i < str.Length; i++) {
freq[str[i] - 'a' ]++;
}
int freq1 = 0, count_freq1 = 0;
for (i = 0; i < CHARS; i++) {
if (freq[i] != 0) {
freq1 = freq[i];
count_freq1 = 1;
break ;
}
}
int j, freq2 = 0, count_freq2 = 0;
for (j = i + 1; j < CHARS; j++) {
if (freq[j] != 0) {
if (freq[j] == freq1) {
count_freq1++;
} else {
count_freq2 = 1;
freq2 = freq[j];
break ;
}
}
}
for ( int k = j + 1; k < CHARS; k++) {
if (freq[k] != 0) {
if (freq[k] == freq1) {
count_freq1++;
}
if (freq[k] == freq2) {
count_freq2++;
} else
{
return false ;
}
}
if (count_freq1 > 1 && count_freq2 > 1) {
return false ;
}
}
return true ;
}
public static void Main() {
String str = "abcbc" ;
if (isValidString(str)) {
Console.WriteLine( "YES" );
} else {
Console.WriteLine( "NO" );
}
}
}
|
Javascript
<script>
let CHARS = 26;
function isValidString(str)
{
let freq = new Array(CHARS);
for (let i=0;i<CHARS;i++)
{
freq[i]=0;
}
for (let i = 0; i < str.length; i++) {
freq[str[i].charCodeAt(0) - 'a' .charCodeAt(0)]++;
}
let i, freq1 = 0, count_freq1 = 0;
for (i = 0; i < CHARS; i++) {
if (freq[i] != 0) {
freq1 = freq[i];
count_freq1 = 1;
break ;
}
}
let j, freq2 = 0, count_freq2 = 0;
for (j = i + 1; j < CHARS; j++) {
if (freq[j] != 0) {
if (freq[j] == freq1) {
count_freq1++;
} else {
count_freq2 = 1;
freq2 = freq[j];
break ;
}
}
}
for (let k = j + 1; k < CHARS; k++) {
if (freq[k] != 0) {
if (freq[k] == freq1) {
count_freq1++;
}
if (freq[k] == freq2) {
count_freq2++;
} else
{
return false ;
}
}
if (count_freq1 > 1 && count_freq2 > 1) {
return false ;
}
}
return true ;
}
let str = "abcbc" ;
if (isValidString(str)) {
document.write( "YES" );
} else {
document.write( "NO" );
}
</script>
|
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.
Check equal frequency of distinct characters in string with 1 or 0 removals using Hashing:
Uses a hashmap to count character frequencies and verifies that there are at most two distinct characters with different frequencies.
Below is the implementation.
C++
#include <bits/stdc++.h>
using namespace std;
bool checkForVariation(string str)
{
if (str.empty() || str.length() != 0) {
return true ;
}
unordered_map< char , int > mapp;
for ( int i = 0; i < str.length(); i++) {
mapp[str[i]]++;
}
bool first = true , second = true ;
int val1 = 0, val2 = 0;
int countOfVal1 = 0, countOfVal2 = 0;
map< char , int >::iterator itr;
for (itr = mapp.begin(); itr != mapp.end(); ++itr) {
int i = itr->first;
if (first) {
val1 = i;
first = false ;
countOfVal1++;
continue ;
}
if (i == val1) {
countOfVal1++;
continue ;
}
if (second) {
val2 = i;
countOfVal2++;
second = false ;
continue ;
}
if (i == val2) {
countOfVal2++;
continue ;
}
return false ;
}
if (countOfVal1 > 1 && countOfVal2 > 1) {
return false ;
}
else {
return true ;
}
}
int main()
{
if (checkForVariation( "abcbcvf" ))
cout << "true" << endl;
else
cout << "false" << endl;
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class AllCharsWithSameFrequencyWithOneVarAllowed {
public static boolean checkForVariation(String str) {
if (str == null || str.isEmpty()) {
return true ;
}
Map<Character, Integer> map = new HashMap<>();
for ( int i = 0 ; i < str.length(); i++) {
map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0 ) + 1 );
}
Iterator<Integer> itr = map.values().iterator();
boolean first = true , second = true ;
int val1 = 0 , val2 = 0 ;
int countOfVal1 = 0 , countOfVal2 = 0 ;
while (itr.hasNext()) {
int i = itr.next();
if (first) {
val1 = i;
first = false ;
countOfVal1++;
continue ;
}
if (i == val1) {
countOfVal1++;
continue ;
}
if (second) {
val2 = i;
countOfVal2++;
second = false ;
continue ;
}
if (i == val2) {
countOfVal2++;
continue ;
}
return false ;
}
if (countOfVal1 > 1 && countOfVal2 > 1 ) {
return false ;
} else {
return true ;
}
}
public static void main(String[] args)
{
System.out.println(checkForVariation( "abcbc" ));
}
}
|
Python3
def checkForVariation(strr):
if ( len (strr) = = 0 ):
return True
mapp = {}
for i in range ( len (strr)):
if strr[i] in mapp:
mapp[strr[i]] + = 1
else :
mapp[strr[i]] = 1
first = True
second = True
val1 = 0
val2 = 0
countOfVal1 = 0
countOfVal2 = 0
for itr in mapp:
i = itr
if (first):
val1 = i
first = False
countOfVal1 + = 1
continue
if (i = = val1):
countOfVal1 + = 1
continue
if (second):
val2 = i
countOfVal2 + = 1
second = False
continue
if (i = = val2):
countOfVal2 + = 1
continue
if (countOfVal1 > 1 and countOfVal2 > 1 ):
return False
else :
return True
print (checkForVariation( "abcbc" ))
|
C#
using System;
using System.Collections.Generic;
public class AllCharsWithSameFrequencyWithOneVarAllowed
{
public static bool checkForVariation(String str)
{
if (str == null || str.Length != 0)
{
return true ;
}
Dictionary< char , int > map = new Dictionary< char , int >();
for ( int i = 0; i < str.Length; i++)
{
if (map.ContainsKey(str[i]))
map[str[i]] = map[str[i]]+1;
else
map.Add(str[i], 1);
}
bool first = true , second = true ;
int val1 = 0, val2 = 0;
int countOfVal1 = 0, countOfVal2 = 0;
foreach (KeyValuePair< char , int > itr in map)
{
int i = itr.Key;
if (first)
{
val1 = i;
first = false ;
countOfVal1++;
continue ;
}
if (i == val1)
{
countOfVal1++;
continue ;
}
if (second)
{
val2 = i;
countOfVal2++;
second = false ;
continue ;
}
if (i == val2)
{
countOfVal2++;
continue ;
}
return false ;
}
if (countOfVal1 > 1 && countOfVal2 > 1)
{
return false ;
}
else
{
return true ;
}
}
public static void Main(String[] args)
{
Console.WriteLine(checkForVariation( "abcbc" ));
}
}
|
Javascript
<script>
function checkForVariation(str)
{
if (str == null || str.length==0) {
return true ;
}
let map = new Map();
for (let i = 0; i < str.length; i++) {
if (!map.has(str[i]))
map.set(str[i],0);
map.set(str[i], map.get(str[i]) + 1);
}
let first = true , second = true ;
let val1 = 0, val2 = 0;
let countOfVal1 = 0, countOfVal2 = 0;
for (let [key, value] of map.entries()) {
let i = value;
if (first) {
val1 = i;
first = false ;
countOfVal1++;
continue ;
}
if (i == val1) {
countOfVal1++;
continue ;
}
if (second) {
val2 = i;
countOfVal2++;
second = false ;
continue ;
}
if (i == val2) {
countOfVal2++;
continue ;
}
return false ;
}
if (countOfVal1 > 1 && countOfVal2 > 1) {
return false ;
} else {
return true ;
}
}
document.write(checkForVariation( "abcbc" ));
</script>
|
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(N)
This article is contributed by Nishant_singh(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.