# How to Count Character Occurrences in a String Using JavaScript

0

This question was asked many times in Frontend Engineer Coding Interviews, in JavaScript, there are many scenarios where we need to count the occurrences of each character in a string. For example, we might want to analyze the frequency of each character in a text document or validate the uniqueness of characters in a password.

In this blog post, we will learn how to count character occurrences in a string using JavaScript, with an efficient implementation that has a time complexity of O(n).

Problem Statement:

Given a string, we need to create an object that represents the character frequencies as keys and their counts as values.

Example:

Let's consider the following input string:

const string = "hello";

Expected Output:

Output: { h: 1, e: 1, l: 2, o: 1 }

where the object represents the character frequencies as keys and their counts as values.

Solution Approach:

• We can approach this problem by iterating through each character of the string and keeping track of the counts in an object. Here's a step-by-step explanation of the implementation:
• Declare an empty object result that will store the character frequencies as keys and their counts as values.
• Use a for loop to iterate through each character of the input string. We can use the str.length property to determine the length of the string and loop through each character using an index variable.
• Inside the loop, retrieve the character at the current index using str[i] and store it in a variable char.
• Check if the char is already a key in the result object. We can use the bracket notation result[char] to access the value associated with the char key.
• If char is key in the result object, increment the count by 1 using result[char] += 1.
• If char is not a key in the result object, add it as a key with a count of 1 using result[char] = 1.
• Continue the loop until all characters in the string have been processed.
• After the loop completes, the result object will contain the character frequencies as keys and their counts as values.
Finally, return the result object as the output of the function.

Code Implementation:

Here's the JavaScript code that implements the solution approach:

function result(str){
const res = {};
for(let i = 0; i<str.length; i++)
{
if(result[str[i]])
{
res[str[i]] +=1;
}
else res[str[i]] =1;
}
return res;
}
const string = "hello";
console.log(result(string))
// Output: { h: 1, e: 1, l: 2, o: 1 }

What if the interviewer gives you an Array Of duplicate string instead of a string?

Don't worry here is the right approach :

const countStringOccurrences = (arr) => {
const result = {};
for (let i = 0; i < arr.length; i++) {
const str = arr[i];
if (result[str]) {
result[str] += 1;
} else {
result[str] = 1;
}
}
return result;
};

// Example usage
const arr = ["mohit", "deep", "deep", "neha", "piku", "piku"];
const result = countStringOccurrences(arr);
console.log(result);
// Output: { mohit: 1, deep: 2, neha: 1, piku: 2 }

Conclusion:

The approach remains similar, but we need to make adjustments to handle arrays instead of strings. By iterating through each element in the array and treating them as strings, we can still efficiently count the occurrences of each string and create an object that represents the string frequencies as keys and their counts as values.

Tags