Last active
January 3, 2021 07:05
-
-
Save ShilpiMaurya/1cb153f691f8f6afd8bddd51e9759f17 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//How to find the maximum occurring character in given String? | |
const maxOccuringChar = str => { | |
if (typeof str !== "string" || !str.length) { | |
return null; | |
} | |
const count = {}; | |
let max = 0; | |
let maxChar = null; | |
str.split("").forEach(item => { | |
if (item !== " ") { | |
if (count[item]) { | |
count[item] = count[item] + 1; | |
if (count[item] > max) { | |
max = count[item]; | |
maxChar = item; | |
} | |
} else { | |
count[item] = 1; | |
} | |
} | |
}); | |
return maxChar; | |
}; | |
//Time-complexity: O(n) | |
//Tests | |
const testCase = [ | |
{ input: "", output: null }, | |
{ input: 12345, output: null }, | |
{ input: "shilpa", output: null }, | |
{ input: "shilpi", output: "i" }, | |
{ input: "shilpis", output: "i" }, | |
{ input: "h ak un am a ta ta", output: "a" }, | |
{ input: "hakunamatata", output: "a" } | |
]; | |
testCase.forEach(({ input, output }, index) => { | |
console.log( | |
`TEST CASE:${index} (${input}):(${ | |
maxOccuringChar(input) === output ? "success" : "failure" | |
})` | |
); | |
}); |
Author
ShilpiMaurya
commented
Jan 2, 2021
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment