Last active
April 11, 2021 21:09
-
-
Save joshuamabina/1f01c020e2142a74a9e1f74ccf69e050 to your computer and use it in GitHub Desktop.
Interview Question: Given a text, return the most repeated letter.
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
'use strict'; | |
/** | |
* @function mostRepeatedLetter | |
* @returns object the highest repeating letter and count | |
* | |
* @description | |
* | |
* Given a text: `I want to rock this interview`, return the most repeating letter. | |
* | |
* How it works: | |
* | |
* 1. Returns an object: highest repeating letter and its repeating count. | |
* 2. Handle if `mostRepeaterLetter` receives empty text. | |
* 3. TODO: What if two letters are repeating? | |
* 4. TODO: Use `performance.now()` to measure and improve performance. See https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_now | |
*/ | |
function mostRepeatedLetter(text) { | |
let arr = text.toLowerCase().match(/\p{L}/gu) | |
console.log(arr.toString()); | |
let highestRepeatingCount = 0; | |
let highestRepeatingLetter = null; | |
for (let i = 0; i < arr.length; i++) { | |
for (let j = 0; j < arr.length; j++) { | |
console.log({ | |
'# of pass': i + 1, | |
'arr[i]': arr[i], | |
'arr[j]:': arr[j], | |
}); | |
if (highestRepeatingCount === 0 && arr[i] === arr[j]) { | |
highestRepeatingCount++; | |
highestRepeatingLetter = arr[i]; | |
// cleanup | |
arr[j] = ''; | |
// console.log({'i': `${i}`, 'j': `${j}`}); | |
} else if (highestRepeatingCount !== 0 && highestRepeatingLetter === arr[i] && arr[i] === arr[j]) { | |
highestRepeatingCount++; | |
highestRepeatingLetter = arr[i]; | |
// cleanup | |
arr[j] = ''; | |
// console.log({'i': `${i}`, 'j': `${j}`}); | |
} | |
} | |
} | |
return { | |
count: highestRepeatingCount, | |
letter: highestRepeatingLetter, | |
}; | |
} | |
const givenText = "I want to rock this interview"; | |
const highestRepeating = mostRepeatedLetter(givenText); | |
console.log('Most repeated letter:', highestRepeating.letter); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment