DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Sherlock and the Valid String

function isValid(s) {
  let hash = {};

  for (let i = 0; i < s.length; i++) {
    let key = s[i];
    if (hash[key]) {
      hash[key]++;
    } else {
      hash[key] = 1;
    }
  }

  let frequencies = [];
  for (let key in hash) {
    frequencies.push(hash[key]);
  }

  frequencies.sort();
  let first = frequencies[0];
  let second = frequencies[1];
  let secondLast = frequencies[frequencies.length - 2];
  let last = frequencies[frequencies.length - 1];

  // If first and last are same, then all frequencies are same
  if (first == last) {
    return "YES";
  }
  // If first is 1, and all other characters have 1 frequency
  if (first == 1 && second == last) {
    return "YES";
  }
  // If all are same and last character has just 1 extra count
  if (first == second && second == secondLast && secondLast == last - 1) {
    return "YES";
  }
  // else NO
  return "NO";
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)