?? JavaScript Interview Challenge - Day 2??
Sanjeev Kumar
Senior Developer | Backend Development Specialist in Node.js & MongoDB | Angular Expertise for Dynamic Frontend Solutions | AWS
Challenge: Can you create a JavaScript function to find the character that repeats the most in a given string?
let str = "hello world";
So in this string you have to return i. it's repeating 3 times.
Instructions:
领英推荐
?? Challenge Yourself! ??
Take on this captivating JavaScript interview problem and see if you can solve it without peeking at the solution!
Solution :
function findMaxRepeatingChar(str) {
if (str.length === 0) {
return null; // Return null for an empty string
}
let charMap = {}; // Object to store character frequencies
// Loop through the string to count character frequencies
for (let char of str) {
charMap[char] = (charMap[char] || 0) + 1;
}
let maxChar = '';
let maxCount = 0;
// Loop through the character map to find the character with the maximum frequency
for (let char in charMap) {
if (charMap[char] > maxCount) {
maxChar = char;
maxCount = charMap[char];
}
}
return maxChar;
}
// Example usage:
const exampleString = "hello world";
const maxRepeatingChar = findMaxRepeatingChar(exampleString);
console.log("Maximum repeating character:", maxRepeatingChar); // Output: 'l'
This approach efficiently counts the occurrences of each character using an object (hash map) and then finds the character with the highest frequency through iteration.
Angular developer
1 年let abc = "hello world"; let maxChar; let maxCount = 0; for (i = 0; i < abc.length; i++) { let count = 0; for (j = 0; j < i + 1; j++) { if (abc[i] === abc[j]) { count++; } } if (count > maxCount) { maxCount = count; maxChar = abc[i]; } } console.log(maxChar, maxCount)
CTO at Livares Technologies Pvt. Ltd. | Software Architect | Quantum Computing & Machine Learning Enthusiast
1 年*Simple Approach* Initialize maxChar='' and maxCount=0. Iterate through string each char. Take count of each char and store as key-value pairs. When a count is higher than maxCount or maxChar is empty, assign count to maxCount and char to maxChar. After the loop print maxChar. Time complexity O(n) Space complexity O(n)
Frontend Developer
1 年https://codepen.io/eastcoastdeveloper/pen/LYaJeOp?editors=0010
Senior Software Engineer @ Uneecops Technologies Ltd. | MCA
1 年Thank for sharing Sanjeev Kumar