Minimum Number of Pushes to Type Word II - Counting & Greedy [JS]

Description 

Solution: Counting & Greedy

It is optimal to assign characters with the most occurances to the front positions on the keys.

  1. Count the occurances of each character.
  2. Collect the counts and sort them in desc order.
  3. 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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]