Skip to content

Instantly share code, notes, and snippets.

@sembug
Created February 7, 2021 12:15
Show Gist options
  • Save sembug/1648b1ea8680f3dcdc7b84362f017cd8 to your computer and use it in GitHub Desktop.
Save sembug/1648b1ea8680f3dcdc7b84362f017cd8 to your computer and use it in GitHub Desktop.
CleverCountLetters.js
// 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