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" | |
})` | |
); | |
}); |
//How do you swap two numbers without using the third variable?
const swapNumbers = (num1, num2) => {
if (!Number.isInteger(num1) || !Number.isInteger(num2) || !num1 || !num2) {
return null;
}
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
console.log(num1, num2);
};
//tests
swapNumbers(1, 2);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect.
Two suggestions:
Use of
for - in
is ok in this case but we aware of its limitation.https://www.reddit.com/r/javascript/comments/8emf94/forin_vs_objectkeys/dxwecvs?utm_source=share&utm_medium=web2x&context=3
Instead of remvoing white-spaces at top-level, you can put that check inside the count-loop (at after line #13), saving one iteration (on line #8).