Minimum Number of Pushes to Type Word II - Counting & Greedy [JS]
Solution: Counting & Greedy
It is optimal to assign characters with the most occurances to the front positions on the keys.
- Count the occurances of each character.
- Collect the counts and sort them in desc order.
- Greedily assign characters with the most occurances to the front positions.
- Assign the first eight counts to the first positions in the eight keys.
- Assign the second eight counts to the second positions in the eight keys.
- ... and so on.
Time Complexity: O(n)
Space Complexity: O(1)
var minimumPushes = function(word) {
let count = Array(26).fill(0), n = word.length;
for (let i = 0; i < n; i++) {
count[word.charCodeAt(i) - 97]++;
}
let counts = [];
for (let i = 0; i < 26; i++) {
if (count[i] > 0) counts.push(count[i]);
}
counts.sort((a, b) => b - a);
let ans = 0;
for (let i = 0; i < counts.length; i++) {
let position = Math.floor(i / 8) + 1;
ans += position * counts[i];
}
return ans;
};
Comments
Post a Comment