Sherlock and the Valid String

Sort by

recency

|

54 Discussions

|

  • + 0 comments

    Java Solution

        public static String isValid(String s) {
            Map<String, Integer> cntMap = new HashMap<>();
            int maxCnt = 0;
            int maxVal = 0; 
            int minVal = Integer.MAX_VALUE;
            
            // Set maxVal and cntMap
            for (int i = 0; i < s.length(); i++) {
                String key = s.substring(i, i + 1);
                int val = cntMap.compute(key, (k,v) -> v == null ? 1 : v + 1);
                if (val > maxVal) maxVal = val;
            }
            
            // Set minVal and maxCnt
            for (int value : cntMap.values()) {
                if (value == maxVal) maxCnt++;
                if (value < minVal) minVal = value;
            }
            
            boolean valid = maxVal == minVal
                || minVal == 1 && maxCnt == cntMap.size() - 1
                || maxVal - minVal == 1 && maxCnt == 1;
            return valid ? "YES" : "NO";
        }
    
  • + 0 comments

    Python 3.10+ solution:

    #!/bin/python3
    
    import os
    from collections import Counter
    from typing import Literal
    
    #
    # Complete the 'is_valid' function below.
    #
    # The function is expected to return a STRING.
    # The function accepts STRING s as parameter.
    #
    
    
    def is_valid(s: str) -> Literal["NO", "YES"]:
        """Given a string, determine if it is valid."""
        y = "YES"
        if len(s) == 1:  # optional
            return y
        match len(counts := {*(frequencies := Counter(s).values())}):
            case 1:
                return y
            case 2:
                meta_freq = Counter(frequencies)
                lo, hi = sorted(counts)
                if 1 == lo == meta_freq[lo]:
                    return y
                if 1 == hi - lo == meta_freq[hi]:
                    return y
        return "NO"
    
    
    if __name__ == "__main__":
        result = is_valid(input())
        with open(os.environ["OUTPUT_PATH"], "w") as fptr:
            fptr.write(f"{result}\n")
    
  • + 0 comments
    #python 3
    def isValid(s):
        keys = set(s)
        frequencies = {key:0 for key in keys}
        for letter in s:
            frequencies[letter] += 1
            
        counts = Counter(frequencies.values())
        maxCount = max(counts.values())
        mode = min([key for key, value in counts.items() if value == maxCount])
        diff = 0
        
        for letter,num in frequencies.items():
            if num != mode:
                if (abs(num - mode) == 1 or num == 1) and diff == 0:
                    diff += 1
                else:
                    return "NO"
        return "YES"
    
  • + 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'