Sherlock and the Valid String

Sort by

recency

|

51 Discussions

|

  • + 0 comments

    Python Solution using a dictionary:

    def isValid(s):
        # Write your code here
        stringDict={}
        
        for letter in s:
            stringDict[letter]= stringDict.get(letter,0) + 1 
        dictValues= list(stringDict.values())
        isRemovedOne=False
        for i in range(1,len(dictValues)):
            diff= abs(dictValues[i]- dictValues[i-1])
            if  diff == 0:
                continue
            else:
                if not isRemovedOne:
                    isRemovedOne=True
                    dictValues[i]-=1
                else:
                    return "NO"
        return "YES"
    
  • + 0 comments

    Best one:

    def isValid(s):
        cts=Counter(s) #Count occurences of string
        ct2=Counter(cts.values()) #Count unique occurences of string occurences
        #if only one item in ct2 then all occurences are equal, 
        #if two items then check if diff is 1 and second most has a count of 1
        #Special case: if the second occurences of occurences equals 1, 
        #it means the second 1 occurrence can be removed to make a valid string.
        kc=ct2.most_common()
        return 'YES' if len(kc)==1 or (len(kc)==2 and \
         (((kc[1][0]-kc[0][0])==1 or kc[1][0]==1) and kc[1][1]==1)) else 'NO'
    
  • + 0 comments

    Python solution using dictionary and set

    def isValid(s):
        # Write your code here
        holder = {}
        for char in s:
            if char in holder:
                holder[char] += 1
            else:
                holder[char] = 1
        val = list(holder.values())
        val.sort()
        test1 = set(val[1:])
        test2 = set(val[:-1])
        test2.add(val[-1]-1)
        result = "YES" if len(test1) == 1 or len(test2) == 1 else "NO"
        return result
    
  • + 0 comments

    What's up with return "YES" or "NO", never heard of booleans ?. That's not how you code.

  • + 0 comments

    def isValid(s):

    l=len(s)
    
    sset=set(s)
    
    if len(set(Counter(s).values()))<=1:
           return "YES"
    
    f=False
    
    for ii in sset:
        if len(set(Counter(s.replace(ii,"",1)).values()))<=1:
            f=True
            break
    
    if f:
        return "YES"
    else:
        return "NO"