
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if frequency of all characters can become same by one removal in Python
Suppose we have a lowercase string s. We have to check whether the frequency of all characters are same after deleting one character or not.
So, if the input is like s = "abbc", then the output will be True as we can delete one b to get string "abc" where frequency of each element is 1.
To solve this, we will follow these steps −
- occurrence := a map with all characters of s and their frequencies
- if occurrences of all characters in s are same, then
- return True
- for each char in s, do
- occurrence[char] := occurrence[char] - 1
- if occurrences of all characters in s are same, then
- return True
- occurrence[char] := occurrence[char] + 1
- return False
Example
Let us see the following implementation to get better understanding −
from collections import defaultdict def allSame(occurrence): counts = list(occurrence.values()) return all(element == counts[0] for element in counts) def solve(s): occurrence = defaultdict(int) for char in s: occurrence[char] += 1 if allSame(occurrence): return True for char in s: occurrence[char] -= 1 if allSame(occurrence): return True occurrence[char] += 1 return False s = "abbc" print(solve(s))
Input
"abbc"
Output
True
- Related Articles
- Check if a string has all characters with same frequency with one variation allowed in Python
- Python dictionary, set and counter to check if frequencies can become same
- Check if frequency of characters are in Recaman Series in Python
- Check if the frequency of all the digits in a number is same in Python
- Meta Strings (Check if two strings can become same after a swap in one string) in C++
- Check if characters of one string can be swapped to form other in Python
- String slicing in Python to check if a can become empty by recursive deletion
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string in Python
- Python program to Rearrange a string so that all same characters become d distance away
- Check if lowercase and uppercase characters are in same order in Python
- Check if a string can become empty by recursively deleting a given sub-string in Python
- Check if both halves of the string have same set of characters in Python
- Python - Check if frequencies of all characters of a string are different
- Python - Check If All the Characters in a String Are Alphanumeric?
- Python - Check if all elements in a List are same

Advertisements