Sherlock and the Valid String

  • + 0 comments

    JavaScript:

    function isValid(s: string): string {
      const charFreq = new Map();
      
      for (let char of s) {
        charFreq.set(char, (charFreq.get(char) || 0) + 1);
      }
      
      const freqCount = new Map();
      for (let freq of charFreq.values()) {
        freqCount.set(freq, (freqCount.get(freq) || 0) + 1);
      }
      
      if (freqCount.size === 1) return "YES";
      if (freqCount.size > 2) return "NO";
      
      const [[freq1, count1], [freq2, count2]] = Array.from(freqCount.entries());
      
      // Check valid conditions
      return (
        (freq1 === 1 && count1 === 1) ||
        (freq2 === 1 && count2 === 1) ||
        (Math.abs(freq1 - freq2) === 1 && (count1 === 1 || count2 === 1))
      ) ? "YES" : "NO";
    }