Problem Description
Given a string word of distinct lowercase letters, remap the keys (from 2 to 9) of a telephone keypad into arbitrary groups such that each letter is assigned to exactly one key. The cost to type a letter is determined by its position on the key (1-indexed). The goal is to minimize the total number of key presses required to type the word.
Key Insights
- Since all letters are distinct and each letter occurs exactly once, frequency does not affect the assignment.
- There are 8 available keys (numbers 2 to 9). The optimal strategy is to assign as many letters as possible to the first position (cost = 1) on each key.
- If more than 8 letters are present, the additional letters must be assigned as the second letter on keys (cost = 2), then third (cost = 3), and so on.
- The total cost for the word is the sum of (1 + the number of full rounds of 8 letters before it) for each letter.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the word. Space Complexity: O(1), using a constant amount of extra space.
Solution
The solution works by iterating over each letter in the given word and calculating the cost based on its position in an optimal assignment. Since there are 8 keys, the first 8 letters cost 1 each, the next 8 cost 2 each, and so on. This is computed by using integer division (i // 8) for each letter's index to determine its cost multiplier. Data structures used are simple counters and loops, making the solution both efficient and straightforward.