diff --git a/readme.md b/readme.md index 1da8e25..9236566 100644 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -## Algorithms (21/ 167) +## Algorithms (22/ 167) | Name | Tags | Solution | | --------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | @@ -14,7 +14,7 @@ | Count Triplets | `Hash Tables` | [TypeScript](./src/algorithms/hashtables/count-triplets) | | Frequency Queries | `Hash Tables` | [TypeScript](./src/algorithms/hashtables/frequency-queries) | | Making Anagrams | `Strings` | [TypeScript](./src/algorithms/strings/make-anagram) | -| Alternating Characters | `Strings` | | +| Alternating Characters | `Strings` | [TypeScript](./src/algorithms/strings/alternating-characters) | | Sherlock and the Valid String | `Strings` | | | Special String Again | `Strings` | | | Common Child | `Strings` | | diff --git a/src/algorithms/strings/alternating-characters/alternating-characters.spec.ts b/src/algorithms/strings/alternating-characters/alternating-characters.spec.ts new file mode 100644 index 0000000..5e3fe72 --- /dev/null +++ b/src/algorithms/strings/alternating-characters/alternating-characters.spec.ts @@ -0,0 +1,23 @@ +import { alternatingCharacters } from './alternating-characters' + +describe('Alternating characters', () => { + test.each([ + { input: 'AAABBBAABB', expected: 6 }, + { input: 'AABBAABB', expected: 4 }, + { input: 'ABABABAA', expected: 1 }, + { input: 'AAABBB', expected: 4 }, + ])( + 'should return the minimum number of required deletions for $input', + ({ input, expected }) => { + expect(alternatingCharacters(input)).toEqual(expected) + } + ) + + it('should handle empty strings', () => { + expect(alternatingCharacters('')).toEqual(0) + }) + + it('should handle single-character strings', () => { + expect(alternatingCharacters('A')).toEqual(0) + }) +}) diff --git a/src/algorithms/strings/alternating-characters/alternating-characters.ts b/src/algorithms/strings/alternating-characters/alternating-characters.ts new file mode 100644 index 0000000..c130e1d --- /dev/null +++ b/src/algorithms/strings/alternating-characters/alternating-characters.ts @@ -0,0 +1,22 @@ +/** + * Given a string containing characters and only. + * The task is to change it into a string such that there are no matching adjacent characters. + * To do this, you are allowed to delete zero or more characters in the string. + * Find the minimum number of required deletions. + * + * E.g + * s = AABAAB // => 2 Deletions + * + */ + +export function alternatingCharacters(s: string): number { + let deletions = 0 + + for (let i = 1; i < s.length; i++) { + if (s[i] === s[i - 1]) { + deletions++ + } + } + + return deletions +}