diff --git a/README.md b/README.md index f06d62f..a46c905 100644 --- a/README.md +++ b/README.md @@ -131,11 +131,12 @@ Ace Coding Interview with 75 Qs | ---------------------------------------- | ---------------- | ------ | | 2215. Find the Difference of Two Arrays | [Solution][2215] | Easy | | 1207. Unique Number of Occurrences | [Solution][1207] | Easy | -| 1657. Determine if Two Strings Are Close | Solution | Medium | +| 1657. Determine if Two Strings Are Close | [Solution][1657] | Medium | | 2352. Equal Row and Column Pairs | Solution | Medium | [2215]: ./src/page-21/2215.%20Find%20the%20Difference%20of%20Two%20Arrays/findDifference.ts [1207]: ./src/page-12/1207.%20Unique%20Number%20of%20Occurrences/uniqueOccurrences.ts +[1657]: ./src/page-16/1657.%20Determine%20if%20Two%20Strings%20Are%20Close/closeStrings.ts | Stack | | | | ---------------------------------- | -------- | ------ | diff --git a/src/page-16/1657. Determine if Two Strings Are Close/closeStrings.test.ts b/src/page-16/1657. Determine if Two Strings Are Close/closeStrings.test.ts new file mode 100644 index 0000000..eb4b906 --- /dev/null +++ b/src/page-16/1657. Determine if Two Strings Are Close/closeStrings.test.ts @@ -0,0 +1,9 @@ +import { closeStrings } from './closeStrings'; + +describe('1657. Determine if Two Strings Are Close', () => { + test('closeStrings', () => { + expect(closeStrings('abc', 'bca')).toBe(true); + expect(closeStrings('a', 'aa')).toBe(false); + expect(closeStrings('cabbba', 'abbccc')).toBe(true); + }); +}); diff --git a/src/page-16/1657. Determine if Two Strings Are Close/closeStrings.ts b/src/page-16/1657. Determine if Two Strings Are Close/closeStrings.ts new file mode 100644 index 0000000..77019c5 --- /dev/null +++ b/src/page-16/1657. Determine if Two Strings Are Close/closeStrings.ts @@ -0,0 +1,35 @@ +type CloseStrings = (word1: string, word2: string) => boolean; + +/** + * Accepted + */ +export const closeStrings: CloseStrings = (word1, word2) => { + if (word1.length !== word2.length) return false; + + const getCharFrequency = (word: string) => { + const frequencyMap = new Map(); + + for (const char of word) { + frequencyMap.set(char, (frequencyMap.get(char) || 0) + 1); + } + + return frequencyMap; + }; + + const frequency1 = getCharFrequency(word1); + const frequency2 = getCharFrequency(word2); + + const keys1 = Array.from(frequency1.keys()); + const keys2 = Array.from(frequency2.keys()); + + // Both strings must have the same set of unique characters + if (keys1.length !== keys2.length || !keys1.every((key) => keys2.includes(key))) { + return false; + } + + const values1 = Array.from(frequency1.values()).sort((a, b) => a - b); + const values2 = Array.from(frequency2.values()).sort((a, b) => a - b); + + // Both strings must have the same sorted frequencies of characters + return values1.every((value, index) => value === values2[index]); +};