Skip to content

Commit

Permalink
183rd Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Jul 28, 2024
1 parent 55120a0 commit 78def55
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | | |
| ---------------------------------- | -------- | ------ |
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
});
});
Original file line number Diff line number Diff line change
@@ -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<string, number>();

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]);
};

0 comments on commit 78def55

Please sign in to comment.