Minimum Number of Pushes to Type Word I - Problem

You are given a string word containing distinct lowercase English letters.

Telephone keypads have keys mapped with distinct collections of lowercase English letters, which can be used to form words by pushing them. For example, the key 2 is mapped with ["a","b","c"], we need to push the key one time to type "a", two times to type "b", and three times to type "c".

It is allowed to remap the keys numbered 2 to 9 to distinct collections of letters. The keys can be remapped to any amount of letters, but each letter must be mapped to exactly one key.

You need to find the minimum number of times the keys will be pushed to type the string word.

Return the minimum number of pushes needed to type word after remapping the keys.

Input & Output

Example 1 — Basic Case
$ Input: word = "abcde"
Output: 5
💡 Note: Each character appears once. Assign each to position 1 on different keys: a(1×1) + b(1×1) + c(1×1) + d(1×1) + e(1×1) = 5
Example 2 — Frequency Matters
$ Input: word = "aabbbc"
Output: 7
💡 Note: c appears 3 times, b appears 2 times, a appears 2 times. Assign c, b, a to position 1 on keys 2, 3, 4: c(3×1) + b(2×1) + a(2×1) = 7
Example 3 — Single Character
$ Input: word = "aaa"
Output: 3
💡 Note: Only character 'a' appears 3 times. Assign to position 1: a(3×1) = 3

Constraints

  • 1 ≤ word.length ≤ 105
  • word consists of distinct lowercase English letters

Visualization

Tap to expand
Minimum Pushes: Optimal Keypad AssignmentInput: word = "abcde"abcdeOptimal Assignment: Each char gets position 1Key 2a (1 press)Key 3b (1 press)Key 4c (1 press)Key 5d (1 press)Key 6e (1 press)Total Presses: 1+1+1+1+1 = 5Output: 5
Understanding the Visualization
1
Input Word
Given word with distinct lowercase letters
2
Count & Sort
Count frequency of each character and sort by frequency
3
Optimal Assignment
Assign most frequent characters to easiest positions
Key Takeaway
🎯 Key Insight: Use greedy assignment to put most frequent characters in positions requiring fewest presses
Asked in
Google 25 Microsoft 20 Amazon 15
23.4K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen