Check if a string has all characters with same frequency with one variation allowed in Python

PythonServer Side ProgrammingProgramming

Suppose we have a lowercase string s, we have to check whether we can convert s into a valid string by deleting at most 1 character. Here a valid string means a string str such that for all unique characters in str each character’s frequency is same.

So, if the input is like s = "xyyzx", then the output will be True as we can delete z then string will be "xyyx" where occurrences of x and y are same.

To solve this, we will follow these steps −

  • size := 26
  • occurrence := an array of size 26. This is storing frequencies of each character in s
  • occr1 := 0
  • occr1_cnt := 0
  • for i in range 0 to size - 1, do
    • if occurrence[i] is not 0, then
      • occr1 := occurrence[i]
      • occr1_cnt := 1
      • come out from loop
  • occr2 := 0
  • occr2_cnt := 0
  • for j in range i+1 to size - 1, do
    • if occurrence[j] is not 0, then
      • if occurrence[j] is same as occr1, then
        • occr1_cnt := occr1_cnt + 1
      • otherwise,
        • occr2_cnt := 1
        • occr := occurrence[j]
        • come out from loop
  • for k in range j+1 to size - 1, do
    • if occurrence[k] is not 0, then
      • if occurrence[k] is same as occr1, then
        • occr1_cnt := occr1_cnt + 1
      • if occurrence[k] is same as occr2, then
        • occr2_cnt := occr2_cnt + 1
      • otherwise,
        • return False
    • if occr1_cnt > 1 and occr2_cnt > 1, then
      • return False
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

size = 26
def solve(str):
   occurrence = [0]*size
   for i in range(len(str)): occurrence[ord(str[i])-ord('a')] += 1
      occr1 = 0
      occr1_cnt = 0
      for i in range(size):
         if (occurrence[i] != 0):
            occr1 = occurrence[i]
            occr1_cnt = 1
            break
   occr2 = 0
   occr2_cnt = 0
   for j in range(i+1,size):
      if (occurrence[j] != 0):
         if (occurrence[j] == occr1):
            occr1_cnt += 1
         else:
            occr2_cnt = 1
            occr = occurrence[j]
            break
   for k in range(j+1,size):
      if occurrence[k] != 0:
         if (occurrence[k] == occr1):
            occr1_cnt += 1
      if (occurrence[k] == occr2):
         occr2_cnt += 1
      else:
         return False
      if occr1_cnt > 1 and occr2_cnt > 1:
         return False
   return True
s = "xyyzx"
print(solve(s))

Input

"xyyzx"

Output

True
raja
Published on 29-Dec-2020 13:16:11
Advertisements