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 −

 Live Demo

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

Updated on: 18-Jan-2021

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements