How to use Object In Javascript
In this method, we will iterate through the array values and store each one of them in an JavaScript object as a key and their count as their values, then we iterate through the object to check the maimum frequency character.
Example: The below code will explain how to implement above-discussed approach in JavaScript.
Javascript
function findMaxFrequencyChar(inputString) { let charFrequency = {}; for (let char of inputString) { if (charFrequency[char]) { charFrequency[char]++; } else { charFrequency[char] = 1; } } let maxFreq = 0; let maxFreqChar = '' ; for (let char in charFrequency) { if (charFrequency[char] > maxFreq) { maxFreq = charFrequency[char]; maxFreqChar = char; } } return maxFreqChar; } const str1 = "abcdabac" ; const str2 = "bZzDbc" ; const maxFreChar1 = findMaxFrequencyChar(str1); const maxFreChar2 = findMaxFrequencyChar(str2); console.log (`The maximum frequency character in string ${str1} is ${maxFreChar1}`); console.log (`The maximum frequency character in string ${str2} is ${maxFreChar2}`); |
The maximum frequency character in string abcdabac is a The maximum frequency character in string bZzDbc is b
Time complexity: O(N+M), where N is the length of given string and M is the number of unique characters in string.
Space complexity: O(N)
Maximum Frequency Character in String in JavaScript
A string is a data structure in JavaScript that is used to store a set of characters. A string can contain a character, a word, or a sentence. A string also can be empty. It is represented using double quotes, single quotes, or template literals.
Examples:
Input: str = "abcdabac"
Output: a
Explanation: In the given string the number of occurrence of character is a is3, b is 2, c is 2, and d is 1.
Therefore 'a' is the character which has maximum frequency.
Input: str = "bZzDbc"
Output: b
Explanation: In the given string the number of occurrence of character is b is 2, Z is 1, z is 1, D is 1, d is 1, c is 1.
Therefore 'a' is the character which has maximum frequency.
We can solve this problem using the methods which are listed below:
Table of Content
- Brute force method
- Using JavaScript Object