Skip to content

Instantly share code, notes, and snippets.

@ShilpiMaurya
Last active January 3, 2021 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShilpiMaurya/1cb153f691f8f6afd8bddd51e9759f17 to your computer and use it in GitHub Desktop.
Save ShilpiMaurya/1cb153f691f8f6afd8bddd51e9759f17 to your computer and use it in GitHub Desktop.
//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"
})`
);
});
@vbkmr
Copy link

vbkmr 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
Copy link
Author

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