Sherlock and the Valid Strings

 This was a medium level problem, it gave me quite a headache as I had to think about very tricky corner cases in this. We just had to return Yes if a string in valid, that is if every element in the string has occurred same number of times, also the string will be valid if we can remove just 1 element from the string from just 1 index otherwise the string will be invalid, so will return No. 

I had the basic idea that, I will be using the Counter module of Python for this and this is a perfect example of when to use python in competitive programming, also I had two conditions in mind that when we will have just 1 frequency in the entire list for every elem we will return Yes and if there are more than 2 frequencies then we will return No. Then I had to think for the condition of just frequencies but that took me around 30 minutes to resolve, maybe cause I am feeling little bit sleepy... well the remaining part was that if smaller frequency of the 2 frequencies has came for just once and is 1 then we can remove that element and then will have just 1 frequency in the entire list. Lastly we check if the greater frequency has came just once and the difference between the 2 frequencies is 1, so we can remove 1 element and make all frequencies equal.

It's 11:27 p.m. and I think I will hit the bed at around 12:00 cause I need to have enough sleep or I wouldn't be able to concentrate without less than 8 hours of sleep, maybe some duo before it and then hit the hay.


The code that passes all the test cases is below:

def isValid(s):
    # Write your code here
    C1=cn(s)
    f_list=list(C1.values())
    f_set=list(set(C1.values()))
    if len(f_set)==1:
        return "YES"
    
    if len(f_set)>2:
        return "NO"
        
    # Getting both frequencies
    m_f=max(f_set[0],f_set[1])
    min_f=min(f_set[0],f_set[1])
    
    # Getting the count of the greater frequency 
    m_f_count=f_list.count(m_f)
    # Count Of smaller frequency
    min_f_count=f_list.count(min_f)
    
    if min_f==1 and min_f_count==1:
        return "YES"
    if min_f==1:
        return "NO"
    if m_f_count==1 and m_f-min_f==1:
        return "YES"
        
    if m_f_count>1:
        return "NO"
        
    return "NO"

Comments

Popular Posts