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 −
Let us see the following implementation to get better understanding −
size = 26 def solve(str): occurrence = *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))