Show problems as
Classic problem #3016MediumHash TableStringGreedySortingCounting

Minimum Number of Pushes to Type Word II

Real-world version: Fewest Presses on a Letter Pad
Tracked in this browser only
Read Minimum Number of Pushes to Type Word II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A pad has eight keys free for letters. Every one of the twenty-six letters is placed on exactly one key, and a key may hold any number of them in any order. A letter placed p-th on its key takes p presses each time it is typed.

Choose the arrangement that makes typing word cost as little as possible, and return that number of presses.

Examples

Example 1

Input
s = "abcdefghi"
Output
10

Nine distinct letters are typed once each. Eight of them take a first place on the eight keys at one press apiece, and the ninth has to share a key, costing two.

Example 2

Input
s = "aaaaabbbbcccdde"
Output
15

Only five distinct letters appear, so each gets a key to itself and every press costs one, giving the length of the word.

Example 3

Input
s = "zzzzzzzz"
Output
8

One letter on its own key costs a single press each time.

Constraints

  • 1 <= word.length <= 10^5
  • word consists of lowercase English letters only

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def minimum_pushes(word: str) -> int:
Java
public int minimumPushes(String word)