Skip to content

2268. Minimum Number of Keypresses 👍

  • 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
class Solution {
 public:
  int minimumKeypresses(string s) {
    int ans = 0;
    vector<int> count(26);

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

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

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

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int minimumKeypresses(String s) {
    int ans = 0;
    Integer[] count = new Integer[26];
    Arrays.fill(count, 0);

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

    Arrays.sort(count, Comparator.reverseOrder());

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

    return ans;
  }
}
1
2
3
4
class Solution:
  def minimumKeypresses(self, s: str) -> int:
    return sum(c * (i // 9 + 1)
               for i, c in enumerate(sorted(Counter(s).values(), reverse=True)))