Skip to content

Commit 6e5b6d5

Browse files
Added solution for leet code 1647
1 parent f7a347a commit 6e5b6d5

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ Happy to accept any contributions to this in any langugage.
5757
22. [Leet Code 445 - Add Numbers II](https://leetcode.com/problems/add-two-numbers-ii/) | [Solution 1](./level_medium/LeetCode%20445_Add%202%20Numbers_1.ts) | [Solution 2](./level_medium/LeetCode%20445_Add%202%20Numbers_2.ts)
5858
23. [Leet Code 59 - Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [Solution](level_medium/SpiralMatrixII.ts)
5959
24. [Leet Code 151 - Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [Solution](level_medium/LeetCode_151_Reverse_Words_In_a_String.ts)
60-
60+
25. [Leet Code 1647 - Minimum Deletions to Make Character Frequency Unique](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/) | [Solution](level_medium/LeetCode_1647_Min_Deletions_For_Unique_Freq.ts)
6161

6262

6363
## Hard
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Leet Code 1647
3+
*
4+
* Solution uses the greedy algorithm, since we can only delete characters and not add characters. Since, we can
5+
* only delete characters, we can start deleting from any order as far as we are ensuring the unique property.
6+
*
7+
* In order to achieve that, we count the frequency of each character. Once, it is done, we keep track of a seen
8+
* collection (maintained by the set) which tracks whether a particular frequency has been seen before for any
9+
* char. Since, the frequency has to be unique, we need to delete characters, if we find something which is already
10+
* existing. If the non-unique frequency is found, we can delete the characters, till we find a unique place for it.
11+
*
12+
* Time: O(n) since each char is visited once. Space: O(1) since fixed storage is used.
13+
*
14+
* @param s
15+
*/
16+
function minDeletions(s: string): number {
17+
18+
// Count Frequency of each character.
19+
const freq = Array(26).fill(0)
20+
for (let idx = 0; idx < s.length; idx++)
21+
freq[s.charCodeAt(idx) - 97]++
22+
23+
24+
// Make necessary deletions to keep the duplicates unique with greedy approach (1st one first).
25+
let deletions = 0;
26+
const uniqFreq = new Set<number>()
27+
for (let idx = 0; idx < 26; idx++) {
28+
// Keep deleting the char till we find a frequency of the char which is unique (till now - greedily)
29+
while(freq[idx] > 0 && uniqFreq.has(freq[idx])) {
30+
deletions++
31+
freq[idx]--
32+
}
33+
uniqFreq.add(freq[idx])
34+
}
35+
36+
return deletions
37+
};

0 commit comments

Comments
 (0)