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)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay