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 to Type Word INPUT word = "abcde" a b c d e Available Keys: 2-9 (8 keys) 2 3 4 5 6 7 8 9 5 distinct letters ALGORITHM STEPS 1 Count Letters n = 5 distinct letters 2 Greedy Assignment First 8 letters: 1 push each 3 Assign to Keys Map each letter to a key Optimal Mapping Key 2: a (1 push) Key 3: b (1 push) Key 4: c (1 push) Key 5: d (1 push) Key 6: e (1 push) 4 Calculate Total Sum = 1+1+1+1+1 = 5 FINAL RESULT Minimum Pushes Required 5 OK Each of 5 letters maps to a unique key Push Count a: 1 push b: 1 push c: 1 push d: 1 push e: 1 push Total: 5 Key Insight: With 8 available keys (2-9), the first 8 letters only need 1 push each. Letters 9-16 need 2 pushes, letters 17-24 need 3 pushes, etc. Formula: For n letters, total = n pushes when n is less than or equal to 8 (all letters get position 1). TutorialsPoint - Minimum Number of Pushes to Type Word I | Greedy Optimal Assignment
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