Find the most recurring character in a string- via JavaScript

Find the most recurring character in a string- via JavaScript

Introduction

This is the fourth post in the series DS & Also Practice - using examples & snippets.

Problem Statement

Given an input string, find the most recurring character.

Ex - "aabbcccdddddd" -> here character d repeats 6 times, hence the most recurring character is d with count as 6.

Implementations

1)

We would somehow need to traverse the input string and create a structure in which we could have every character along with how many times it has been repeated. This kind of structure is called as a character map, and is very useful in string traversal problems.

An object fits well in these kinds of scenarios, for ex - input string "aabbcccdddddd" - the character map object could be as below:

{
a:2,
b:2,
c:3,
d:6
}

Once the character map has been created, we can traverse through the object to return the most recurring character.

Let us see one of the implementations.

//max characters implementation

function maxCharacters(str) {
  const chars = {};
  let maxCount = 0;
  let maxCharacter = "";

  for (let i = 0; i < str.length; i++) {
    let temp = str[i];
    chars[temp] = !chars[temp] ? 1 : chars[temp] + 1;
  }
  //a loop can be run thru an OBJECT via for-in loop
  for (let key in chars) {
    if (chars[key] > maxCount) {
      maxCount = chars[key];
      maxCharacter = key;
    }
  }

  return { maxCharacter, maxCount };
}

console.log(maxCharacters("abbcccccdddddde"));
console.log(maxCharacters("11111 22 3 4 0009999999"));

image.png

Main logic - If there does not exist any value for a character key in the chars object, it is safe to say that the character key has been encountered for the 1st time, hence, to compare it we negate the undefined value to truthy and assign the value as 1 to the key, else we increment the value by 1.

2)

In the second implementation, we would like to clean up the above implementation by replacing the for loop with for of loop, and use the Object.hasOwnProperty() .

//max characters implementation using for-of loop & object.hasOwnProperty() method
function maxCharacters(str) {
  const chars = {};
  let maxCount = 0;
  let maxCharacter = "";

  for (let char of str) {
    chars[char] = chars.hasOwnProperty(char) ? chars[char] + 1 : 1;
  }
  //a loop can be run thru an OBJECT via for-in loop
  for (let key in chars) {
    if (chars[key] > maxCount) {
      maxCount = chars[key];
      maxCharacter = key;
    }
  }

  return { maxCharacter, maxCount };
}

console.log(maxCharacters("abbcccccdddddde"));
console.log(maxCharacters("11111 22 3 4 0009999999"));

image.png

I like this cleaner implementation.

The full code is present at - github.com/anurag1302/dsalgo-javascript/tre..

Did you find this article valuable?

Support Anurag Sinha by becoming a sponsor. Any amount is appreciated!