Check equal frequency of distinct characters in string with 1 or 0 removals
Last Updated :
25 Sep, 2023
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++
// C++ program to check if a string can be made
// valid by removing at most 1 character.
#include <bits/stdc++.h>
using namespace std;
// Assuming only lower case characters
const int CHARS = 26;
// To check a string S can be converted to a “valid” string
// by removing less than or equal to one character.
bool isValidString(string str)
{
int freq[CHARS] = { 0 };
// freq[] : stores the frequency of each character of a
// string
for (int i = 0; i < str.length(); i++)
freq[str[i] - 'a']++;
// Find first character with non-zero frequency
int i, freq1 = 0, count_freq1 = 0;
for (i = 0; i < CHARS; i++) {
if (freq[i] != 0) {
freq1 = freq[i];
count_freq1 = 1;
break;
}
}
// Find a character with frequency different from freq1.
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;
}
}
}
// If we find a third non-zero frequency or count of
// both frequencies become more than 1, then return
// false
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 // If we find a third non-zero freq
return false;
}
// If counts of both frequencies is more than 1
if (count_freq1 > 1 && count_freq2 > 1)
return false;
}
// Return true if we reach here
return true;
}
// Driver code
int main()
{
char str[] = "abcbc";
if (isValidString(str))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// C program to check if a string can be made
// valid by removing at most 1 character.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
// Assuming only lower case characters
const int CHARS = 26;
// To check a string S can be converted to a “valid” string
// by removing less than or equal to one character.
bool isValidString(char str[])
{
int freq[CHARS];
for (int i = 0; i < CHARS; i++)
freq[i] = 0;
// freq[] : stores the frequency of each character of a
// string
for (int i = 0; i < strlen(str); i++)
freq[str[i] - 'a']++;
// Find first character with non-zero frequency
int i, freq1 = 0, count_freq1 = 0;
for (i = 0; i < CHARS; i++) {
if (freq[i] != 0) {
freq1 = freq[i];
count_freq1 = 1;
break;
}
}
// Find a character with frequency different from freq1.
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;
}
}
}
// If we find a third non-zero frequency or count of
// both frequencies become more than 1, then return
// false
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 // If we find a third non-zero freq
return false;
}
// If counts of both frequencies is more than 1
if (count_freq1 > 1 && count_freq2 > 1)
return false;
}
// Return true if we reach here
return true;
}
// Driver code
int main()
{
char str[] = "abcbc";
if (isValidString(str))
printf("YES\n");
else
printf("NO\n");
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java program to check if a string can be made
// valid by removing at most 1 character.
public class GFG {
// Assuming only lower case characters
static int CHARS = 26;
/* To check a string S can be converted to a “valid”
string by removing less than or equal to one
character. */
static boolean isValidString(String str)
{
int freq[] = new int[CHARS];
// freq[] : stores the frequency of each
// character of a string
for (int i = 0; i < str.length(); i++) {
freq[str.charAt(i) - 'a']++;
}
// Find first character with non-zero frequency
int i, freq1 = 0, count_freq1 = 0;
for (i = 0; i < CHARS; i++) {
if (freq[i] != 0) {
freq1 = freq[i];
count_freq1 = 1;
break;
}
}
// Find a character with frequency different
// from freq1.
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;
}
}
}
// If we find a third non-zero frequency
// or count of both frequencies become more
// than 1, then return false
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 // If we find a third non-zero freq
{
return false;
}
}
// If counts of both frequencies is more than 1
if (count_freq1 > 1 && count_freq2 > 1) {
return false;
}
}
// Return true if we reach here
return true;
}
// Driver code
public static void main(String[] args)
{
String str = "abcbc";
if (isValidString(str)) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
// This code is contributed by Aditya Kumar (adityakumar129)
Python3
# Python 3 program to check if
# a string can be made
# valid by removing at most 1 character.
# Assuming only lower case characters
CHARS = 26
# To check a string S can be converted to a “valid”
# string by removing less than or equal to one
# character.
def isValidString(str):
freq = [0]*CHARS
# freq[] : stores the frequency of each
# character of a string
for i in range(len(str)):
freq[ord(str[i])-ord('a')] += 1
# Find first character with non-zero frequency
freq1 = 0
count_freq1 = 0
for i in range(CHARS):
if (freq[i] != 0):
freq1 = freq[i]
count_freq1 = 1
break
# Find a character with frequency different
# from freq1.
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
# If we find a third non-zero frequency
# or count of both frequencies become more
# than 1, then return false
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
# If we find a third non-zero freq
else:
return False
# If counts of both frequencies is more than 1
if (count_freq1 > 1 and count_freq2 > 1):
return False
# Return true if we reach here
return True
# Driver code
if __name__ == "__main__":
str= "abcbc"
if (isValidString(str)):
print("YES")
else:
print("NO")
# this code is contributed by
# ChitraNayal
C#
// C# program to check if a string can be made
// valid by removing at most 1 character.
using System;
public class GFG {
// Assuming only lower case characters
static int CHARS = 26;
/* To check a string S can be converted to a “valid”
string by removing less than or equal to one
character. */
static bool isValidString(String str) {
int []freq = new int[CHARS];
int i=0;
// freq[] : stores the frequency of each
// character of a string
for ( i= 0; i < str.Length; i++) {
freq[str[i] - 'a']++;
}
// Find first character with non-zero frequency
int freq1 = 0, count_freq1 = 0;
for (i = 0; i < CHARS; i++) {
if (freq[i] != 0) {
freq1 = freq[i];
count_freq1 = 1;
break;
}
}
// Find a character with frequency different
// from freq1.
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;
}
}
}
// If we find a third non-zero frequency
// or count of both frequencies become more
// than 1, then return false
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 // If we find a third non-zero freq
{
return false;
}
}
// If counts of both frequencies is more than 1
if (count_freq1 > 1 && count_freq2 > 1) {
return false;
}
}
// Return true if we reach here
return true;
}
// Driver code
public static void Main() {
String str = "abcbc";
if (isValidString(str)) {
Console.WriteLine("YES");
} else {
Console.WriteLine("NO");
}
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to check if a string can be made
// valid by removing at most 1 character.
// Assuming only lower case characters
let CHARS = 26;
/* To check a string S can be converted to a “valid”
string by removing less than or equal to one
character. */
function isValidString(str)
{
let freq = new Array(CHARS);
for(let i=0;i<CHARS;i++)
{
freq[i]=0;
}
// freq[] : stores the frequency of each
// character of a string
for (let i = 0; i < str.length; i++) {
freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
}
// Find first character with non-zero frequency
let i, freq1 = 0, count_freq1 = 0;
for (i = 0; i < CHARS; i++) {
if (freq[i] != 0) {
freq1 = freq[i];
count_freq1 = 1;
break;
}
}
// Find a character with frequency different
// from freq1.
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;
}
}
}
// If we find a third non-zero frequency
// or count of both frequencies become more
// than 1, then return false
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 // If we find a third non-zero freq
{
return false;
}
}
// If counts of both frequencies is more than 1
if (count_freq1 > 1 && count_freq2 > 1) {
return false;
}
}
// Return true if we reach here
return true;
}
// Driver code
let str = "abcbc";
if (isValidString(str)) {
document.write("YES");
} else {
document.write("NO");
}
// This code is contributed by ab2127
</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++
// C++ program to check if a string can be made
// valid by removing at most 1 character using hashmap.
#include <bits/stdc++.h>
using namespace std;
// To check a string S can be converted to a variation
// string
bool checkForVariation(string str)
{
if (str.empty() || str.length() != 0) {
return true;
}
unordered_map<char, int> mapp;
// Run loop from 0 to length of string
for (int i = 0; i < str.length(); i++) {
mapp[str[i]]++;
}
// declaration of variables
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 is true than countOfVal1 increase
if (first) {
val1 = i;
first = false;
countOfVal1++;
continue;
}
if (i == val1) {
countOfVal1++;
continue;
}
// if second is true than countOfVal2 increase
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;
}
}
// Driver code
int main()
{
if (checkForVariation("abcbcvf"))
cout << "true" << endl;
else
cout << "false" << endl;
return 0;
}
// This code is contributed by avanitrachhadiya2155
Java
// Java program to check if a string can be made
// valid by removing at most 1 character using hashmap.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class AllCharsWithSameFrequencyWithOneVarAllowed {
// To check a string S can be converted to a variation
// string
public static boolean checkForVariation(String str) {
if(str == null || str.isEmpty()) {
return true;
}
Map<Character, Integer> map = new HashMap<>();
// Run loop from 0 to length of string
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();
// declaration of variables
boolean first = true, second = true;
int val1 = 0, val2 = 0;
int countOfVal1 = 0, countOfVal2 = 0;
while(itr.hasNext()) {
int i = itr.next();
// if first is true than countOfVal1 increase
if(first) {
val1 = i;
first = false;
countOfVal1++;
continue;
}
if(i == val1) {
countOfVal1++;
continue;
}
// if second is true than countOfVal2 increase
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;
}
}
// Driver code
public static void main(String[] args)
{
System.out.println(checkForVariation("abcbc"));
}
}
Python3
# Python program to check if a string can be made
# valid by removing at most 1 character using hashmap.
# To check a string S can be converted to a variation
# string
def checkForVariation(strr):
if(len(strr) == 0):
return True
mapp = {}
# Run loop from 0 to length of string
for i in range(len(strr)):
if strr[i] in mapp:
mapp[strr[i]] += 1
else:
mapp[strr[i]] = 1
# declaration of variables
first = True
second = True
val1 = 0
val2 = 0
countOfVal1 = 0
countOfVal2 = 0
for itr in mapp:
i = itr
# if first is true than countOfVal1 increase
if(first):
val1 = i
first = False
countOfVal1 += 1
continue
if(i == val1):
countOfVal1 += 1
continue
# if second is true than countOfVal2 increase
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
# Driver code
print(checkForVariation("abcbc"))
# This code is contributed by rag2127
C#
// C# program to check if a string can be made
// valid by removing at most 1 character using hashmap.
using System;
using System.Collections.Generic;
public class AllCharsWithSameFrequencyWithOneVarAllowed
{
// To check a string S can be converted to a variation
// string
public static bool checkForVariation(String str)
{
if(str == null || str.Length != 0)
{
return true;
}
Dictionary<char, int> map = new Dictionary<char, int>();
// Run loop from 0 to length of string
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);
}
// declaration of variables
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 is true than countOfVal1 increase
if(first)
{
val1 = i;
first = false;
countOfVal1++;
continue;
}
if(i == val1)
{
countOfVal1++;
continue;
}
// if second is true than countOfVal2 increase
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;
}
}
// Driver code
public static void Main(String[] args)
{
Console.WriteLine(checkForVariation("abcbc"));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to check if a string can be made
// valid by removing at most 1 character using hashmap.
// To check a string S can be converted to a variation
// string
function checkForVariation(str)
{
if(str == null || str.length==0) {
return true;
}
let map = new Map();
// Run loop from 0 to length of string
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);
}
// declaration of variables
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 is true than countOfVal1 increase
if(first) {
val1 = i;
first = false;
countOfVal1++;
continue;
}
if(i == val1) {
countOfVal1++;
continue;
}
// if second is true than countOfVal2 increase
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;
}
}
// Driver code
document.write(checkForVariation("abcbc"));
// This code is contributed by patel2127
</script>
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(N)
Similar Reads
Check if a substring exists having only 2 distinct characters with frequency of one as twice the others Given a string str[] of N lower case English alphabets, the task is to check if there exists a substring of the given string such that the substring is composed of only two characters and the frequency of 1st character = 2 * frequency of 2nd character. Example: Input: str[] = "aaaabbc"Output: YesExp
6 min read
Count of Substrings with at least K pairwise Distinct Characters having same Frequency Given a string S and an integer K, the task is to find the number of substrings which consists of at least K pairwise distinct characters having same frequency. Examples: Input: S = "abasa", K = 2 Output: 5 Explanation: The substrings in having 2 pairwise distinct characters with same frequency are
7 min read
Check if frequency of all characters can become same by one removal Given a string that 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 the same in the string.Examples: Input: str = âxyyzâ Output: Yes We can remove character âyâ from above string to make th
15+ min read
Count Substrings with even frequency of each character and one exception Given a string S ('a' ? S[i] ? 't') of length N (1 ? N ? 105), which consists of lowercase English alphabets, the task is to count all substrings such that the frequency of all characters should be even or all characters should occur an even number of times except any one character which might occur
6 min read
Check if frequency of each character is equal to its position in English Alphabet Given string str of lowercase alphabets, the task is to check if the frequency of each distinct characters in the string equals to its position in the English Alphabet. If valid, then print "Yes", else print "No". Examples: Input: str = "abbcccdddd" Output: Yes Explanation: Since frequency of each d
8 min read
Count of substrings with the frequency of at most one character as Odd Given a string S of N characters, the task is to calculate the total number of non-empty substrings such that at most one character occurs an odd number of times. Example: Input: S = "aba"Output: 4Explanation: The valid substrings are "a", "b", "a", and "aba". Therefore, the total number of required
7 min read
Minimum removal of subsequences of distinct consecutive characters required to empty a given string Given a binary string, str, the task is to empty the given string by minimum number of removals of a single character or a subsequence containing distinct consecutive characters from str. Examples: Input: str = "0100100111" Output: 3 Explanation: Removing the subsequence "010101" from the string mod
6 min read
Count the sum of count of distinct characters present in all Substrings Given a string S consisting of lowercase English letters of size N where (1 <= N <= 105), the task is to print the sum of the count of distinct characters N where (1 <= N <= 105)in all the substrings. Examples: Input: str = "abbca"Output: 28Explanation: The following are the substrings o
8 min read
Count of strings with frequency of each character at most X and length at least Y Given an array arr[] of strings and integers X and Y, the task is to find the count of strings with frequency of each character at most X and length of the string at least Y. Examples: Input: arr[] = { "ab", "derdee", "erre" }, X = 2, Y = 4Output: 1Explanation: Strings with character frequency at mo
6 min read
Check if characters of a given string can be used to form any N equal strings Given a string S and an integer N, the task is to check if it is possible to generate any string N times from the characters of the given string or not. If it is possible, print Yes. Otherwise, print No. Examples: Input: S = "caacbb", N = 2Output: YesExplanation: All possible strings that can be gen
5 min read