Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//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"
})`
);
});
@vaibhav-kumar-tokyo

This comment has been minimized.

Copy link

@vaibhav-kumar-tokyo vaibhav-kumar-tokyo commented Dec 12, 2020

Perfect.
Two suggestions:

  1. 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

  2. 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).

@ShilpiMaurya

This comment has been minimized.

Copy link
Owner Author

@ShilpiMaurya ShilpiMaurya commented Jan 2, 2021

//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