Skip to content

Instantly share code, notes, and snippets.

@shalomsam
Created June 27, 2021 19:34
Show Gist options
  • Select an option

  • Save shalomsam/ea2369306389968fd866814eddd4208a to your computer and use it in GitHub Desktop.

Select an option

Save shalomsam/ea2369306389968fd866814eddd4208a to your computer and use it in GitHub Desktop.
Minimum Deletions to Make Character Frequencies Unique
type Frequency = { [key: string]: number };
function minDeletions(s: string): number {
const stringArr: string[] = s.split('');
// Get the character frequencies
const freq: Frequency = {};
stringArr.map((str) => {
freq[str] = Number(freq?.[str] || 0) + 1;
});
const values = Object.values(freq);
// highest to lowest
values.sort((a,b) => b-a)
// deletions
let deletions = 0;
// loop through frequency values
for (let i=0; i < values.length; i++) {
// set current value
let n = values[i];
// look ahead in the array to find duplicate frequencies (n)
for (let j = i+1; j < values.length; j++) {
// if look ahead value is non-zero and equal to current number (n)
// then delete one from look ahead value
if (values[j] && n === values[j]) {
values[j]--;
deletions++;
}
}
}
console.log("Deletions > ", deletions);
return deletions;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment