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.
Code Implementation:
Here’s the JavaScript code that implements the solution approach:
What if the interviewer gives you an Array Of duplicate string instead of a string?
Don’t worry here is the right approach :
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.