Given a string s which contains only lower alphabetic characters, check if it is possible to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Return true if it is possible to do else return false.Note: The driver code print 1 if the value returned is true, otherwise 0.
Question
Given a string s which contains only lower alphabetic characters, check if it is possible to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Return true if it is possible to do else return false.Note: The driver code print 1 if the value returned is true, otherwise 0.
Solution
Sure, here is a Python solution for the problem:
def check_string(s):
# Create a dictionary to store the frequency of each character
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# Create a list of the frequencies
freq_list = list(freq.values())
# Check if all frequencies are the same
if len(set(freq_list)) == 1:
return True
# If not, check if it is possible to remove one character to make all frequencies the same
for char in freq:
freq[char] -= 1
temp = list(freq.values())
try:
temp.remove(0)
except:
pass
if len(set(temp)) == 1:
return True
freq[char] += 1
# If it is not possible to make all frequencies the same by removing one character, return False
return False
This function first counts the frequency of each character in the string. If all frequencies are the same, it returns True. If not, it checks if it is possible to make all frequencies the same by removing one character. If it is possible, it returns True. If not, it returns False.
Similar Questions
Reduce a string of lowercase characters in range ascii[‘a’..’z’]by doing a series of operations. In each operation, select a pair of adjacent letters that match, and delete them.Delete as many characters as possible using this method and return the resulting string. If the final string is empty, return Empty String
Write a program to check whether a given character is Alphabet or not using if else statement Note: Check for both upper and lower case characters
Given a string of lowercase alphabets, count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Example 1:Input:S = "aba", K = 2Output:3Explanation:The substrings are: "ab", "ba" and "aba".
Write a program to remove the given character in case of duplicacyFor example, let's say we have s = "Hello", c = 'l', the result will be "Helo"let's say we have s = "Hello World", c = 'l', the result will be "Helo Word"
Problem StatementWrite a program to remove the duplicate characters in the given stringInput FormatGiven a stringOutput Formatremove the duplicate characters and print the unique string
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.