Skip to content

Instantly share code, notes, and snippets.

@motss
Created September 3, 2019 05:58
Show Gist options
  • Save motss/ecb5bc0464db4d7aea803f0b7806043b to your computer and use it in GitHub Desktop.
Save motss/ecb5bc0464db4d7aea803f0b7806043b to your computer and use it in GitHub Desktop.
Alternating characters
// Time complexity: O(n) where n is the number of characters.
// Space complexity: O(1) for a few variables.
function alternatingCharacters(x) {
const len = x.length;
if (len < 2) return 0;
let lastChar = x[0];
let count = 0;
let countA = lastChar === 'a' ? 1 : 0;
let countB = lastChar === 'b' ? 1 : 0;
for (let i = 1; i < len; i += 1) {
const n = x[i];
// If current letter is the same as the last seen letter,
// increment `count`.
if (lastChar === n) count += 1;
if ('a' === n) countA += 1;
if ('b' === n) countB += 1;
lastChar = n;
}
// Here compare for cases where `count` is 0 as all letters
// are alternating but the number of A and the number of B
// are not the same.
return count === 0 ?
Math.abs(countA - countB) :
count;
}
function main() {
const a = [
'aaaa',
'bbbbb',
'abababab',
'bababa',
'aaabbb',
'aaaab',
'bbbbba',
'ababababa',
'bababab',
];
a.forEach((n) => {
console.log('Alternating characters: ', n, alternatingCharacters(n));
});
}
console.clear();
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment