Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active November 5, 2021 21:29
Show Gist options
  • Save mgtitimoli/398377e7e9b886b613cb435e85924e27 to your computer and use it in GitHub Desktop.
Save mgtitimoli/398377e7e9b886b613cb435e85924e27 to your computer and use it in GitHub Desktop.
Find the substring triples count that contain the same amount of "a"
const getAllPartSets = s => {
const partSets = [];
// pivot in 0
for (let i = 2; i < s.length; i++) {
partSets.push([
s[0],
s.slice(1, i),
s.slice(i)
]);
}
// pivot in I
for (let i = 1; i < s.length - 1; i++) {
partSets.push([
s.slice(0, i),
s.slice(i, i + 1),
s.slice(i + 1)
]);
}
// pivot in last
// - we start in 2 as the first part set is the same
// as the last one in the pivot 0
// - we finish in s.length - 2 as the last part set is
// the same as the last one in pivot I
for (let i = 2; i < s.length - 2; i++) {
partSets.push([
s.slice(0, i),
s.slice(i, -1),
s[s.length - 1]
]);
}
return partSets;
};
const getLetterCount = (str, letter) =>
str
.split("")
.filter(curLetter => curLetter === letter)
.length;
const solution = s => {
const filteredLetter = "a";
const allPartSets = getAllPartSets(s);
const filteredPartSets = allPartSets.filter(
partSet => {
const firstPartLetterCount = getLetterCount(partSet[0], filteredLetter);
return partSet
.slice(1)
.every(part => getLetterCount(part, filteredLetter) === firstPartLetterCount);
}
);
return filteredPartSets.length;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment