Created
February 7, 2021 12:15
-
-
Save sembug/1648b1ea8680f3dcdc7b84362f017cd8 to your computer and use it in GitHub Desktop.
CleverCountLetters.js
This file contains hidden or 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
| // https://twitter.com/Al_Grigor/status/1357028887209902088 | |
| /* | |
| Most candidates cannot solve this interview problem: | |
| Input: "aaaabbbcca" | |
| Output: [("a", 4), ("b", 3), ("c", 2), ("a", 1)] | |
| Write a function that converts the input to the output | |
| I ask it in the screening interview and give it 25 minutes | |
| How would you solve it? | |
| */ | |
| var input = 'aaaabbbcca'; | |
| let result = []; | |
| let currentLetter = ''; | |
| for (const item of input) { | |
| if (item !== currentLetter) { | |
| result.push({ | |
| 'letter': item, | |
| 'count': 1 | |
| }); | |
| } else { | |
| result[result.length - 1]['count'] += 1; | |
| } | |
| currentLetter = item; | |
| } | |
| console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment