DEV Community

Cover image for How to check if the occurrence of letters in the given string is the same
Rohit Kumawat
Rohit Kumawat

Posted on Edited on

How to check if the occurrence of letters in the given string is the same

Problem statement: We have to check if all letters in a given string occurred same times.

Examples:

  • dev has three letters and all appeared 1 time. So it will return true.
  • aabbcc has three letters and all appeared 2 times. So it will return true.
  • xyyzzz has three letters and x appeared 1 time, y 2 times, and z 3 times. So it will return false.

Solution:

const str = "aabbcc";
const tracker = {};

for(let i = 0; i < str.length; i++) {
  if(!tracker[str[i]]) {
    tracker[str[i]] = 1;
  } else if (tracker[str[i]]) {
    tracker[str[i]]++;
  }
}

const repeatCount = Object.values(tracker);
const isTrue = repeatCount.every(el => el === repeatCount[0]);

console.log("same occurrence for all letters", isTrue); //true
Enter fullscreen mode Exit fullscreen mode

In this solution:

  • We used for loop and check for each letter's occurrence.
  • Then we kept track of every letter's occurrence in an object.
  • And finally, we checked if the occurrence number is the same for all letters.
  • Time complexity for this solution is O(n).

Conclusion:

There are many solutions to this problem. This is just one of them. I will be adding different solutions in the future in the same post.

Thanks for reading and Happy coding 💻
For more tech and F.R.I.E.N.D.S. discuss, let's connect on Twitter.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.