Sherlock and the Valid String

Sort by

recency

|

50 Discussions

|

  • + 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"    
    
  • + 0 comments
    def isValid(s):
        arr = [0] * 26
        for i in range(len(s)):
            arr[ord(s[i])-97]+=1
        arr.sort(reverse=True)
        if min(arr) == 0:
            arr= arr[:arr.index(0)]
        if len(arr) == 1:
            return "YES"
        mainValue = arr[1]
        firstValue = arr[0]
        lastValue = arr[-1]
        left = CheckIsAllSame(arr[0:len(arr)-1])
        if left and (lastValue == mainValue or lastValue == 1):
            return "YES"
        right = CheckIsAllSame(arr[1:len(arr)])
        if right and (firstValue == mainValue or firstValue == mainValue + 1):
            return "YES"
        return "NO"
    
    def CheckIsAllSame(arr):
        for i in range(len(arr)-1):
            if arr[i] != arr[i+1]:
                return False
        return True