Skip to content

3016. Minimum Number of Pushes to Type Word II 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  // Same as 3014. Minimum Number of Pushes to Type Word I
  int minimumPushes(string word) {
    int ans = 0;
    vector<int> count(26);

    for (const char c : word)
      ++count[c - 'a'];

    ranges::sort(count, greater<>());

    for (int i = 0; i < 26; ++i)
      ans += count[i] * (i / 8 + 1);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  // Same as 3014. Minimum Number of Pushes to Type Word I
  public int minimumPushes(String word) {
    int ans = 0;
    int[] count = new int[26];

    for (final char c : word.toCharArray())
      ++count[c - 'a'];

    Arrays.sort(count);

    for (int i = 0; i < 26; ++i)
      ans += count[26 - i - 1] * (i / 8 + 1);

    return ans;
  }
}
1
2
3
4
5
class Solution:
  # Same as 3014. Minimum Number of Pushes to Type Word I
  def minimumPushes(self, word: str) -> int:
    freqs = sorted(collections.Counter(word).values(), reverse=True)
    return sum(freq * (i // 8 + 1) for i, freq in enumerate(freqs))