3016. Minimum Number of Pushes to Type Word II

You are given a string word containing 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.

An example mapping of letters to keys on a telephone keypad is given below. Note that 1*#, and 0 do not map to any letters.

Example 1:

Input: word = "abcde"
Output: 5
Explanation: The remapped keypad given in the image provides the minimum cost.
"a" -> one push on key 2
"b" -> one push on key 3
"c" -> one push on key 4
"d" -> one push on key 5
"e" -> one push on key 6
Total cost is 1 + 1 + 1 + 1 + 1 = 5.
It can be shown that no other mapping can provide a lower cost.

Example 2:

Input: word = "xyzxyzxyzxyz"
Output: 12
Explanation: The remapped keypad given in the image provides the minimum cost.
"x" -> one push on key 2
"y" -> one push on key 3
"z" -> one push on key 4
Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12
It can be shown that no other mapping can provide a lower cost.
Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters.

Example 3:

Input: word = "aabbccddeeffgghhiiiiii"
Output: 24
Explanation: The remapped keypad given in the image provides the minimum cost.
"a" -> one push on key 2
"b" -> one push on key 3
"c" -> one push on key 4
"d" -> one push on key 5
"e" -> one push on key 6
"f" -> one push on key 7
"g" -> one push on key 8
"h" -> two pushes on key 9
"i" -> one push on key 9
Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24.
It can be shown that no other mapping can provide a lower cost.

Constraints:

  • 1 <= word.length <= 105
  • word consists of lowercase English letters.

Approach 01:

#include <iostream>
#include <vector>
#include <unordered_map>
#include <set>
#include <algorithm>

using namespace std;

class Solution {
public:
    int minimumPushes(string word) {
        int wordLength = word.length();
        set<char> uniqueChars(word.begin(), word.end());
        int numUniqueChars = uniqueChars.size();
        unordered_map<char, int> charFrequency;
        
        // Calculate the frequency of each character in the word
        for (char ch : word) {
            charFrequency[ch]++;
        }

        // If there are 8 or fewer unique characters, return the total number of characters
        if (numUniqueChars <= 8) {
            int totalPushes = 0;
            for (const auto& entry : charFrequency) {
                totalPushes += entry.second;
            }
            return totalPushes;
        }

        int position = 1;
        int totalPushes = 0;
        
        // Get frequencies of characters sorted in descending order
        vector<int> sortedFrequencies;
        for (const auto& entry : charFrequency) {
            sortedFrequencies.push_back(entry.second);
        }
        sort(sortedFrequencies.rbegin(), sortedFrequencies.rend());
        
        // Calculate the total number of pushes based on the position of each character
        for (int frequency : sortedFrequencies) {
            if (position <= 8) {
                totalPushes += frequency;
            } else if (position <= 16) {
                totalPushes += frequency * 2;
            } else if (position <= 24) {
                totalPushes += frequency * 3;
            } else {
                totalPushes += frequency * 4;
            }
            position++;
        }

        return totalPushes;
    }
};
from collections import Counter

class Solution:
    def minimumPushes(self, word: str) -> int:
        wordLength = len(word)
        numUniqueChars = len(set(word))
        charFrequency = Counter(word)
        
        # If there are 8 or fewer unique characters, return the total number of characters
        if numUniqueChars <= 8:
            totalPushes = sum(charFrequency.values())
            return totalPushes
        
        position = 1
        totalPushes = 0

        # Get frequencies of characters sorted in descending order
        sortedFrequencies = sorted(charFrequency.values(), reverse=True)
        
        # Calculate the total number of pushes based on the position of each character
        for frequency in sortedFrequencies:
            if position <= 8:
                totalPushes += frequency
            elif 9 <= position <= 16:
                totalPushes += frequency * 2
            elif 17 <= position <= 24:
                totalPushes += frequency * 3
            else:
                totalPushes += frequency * 4
            position += 1

        return totalPushes

Time Complexity

  • Set Creation:

    Creating a set of unique characters from the string takes \( O(n) \), where \( n \) is the length of the string.

  • Frequency Calculation:

    Calculating the frequency of each character involves iterating through the string, which takes \( O(n) \).

  • Sorting Frequencies:

    Sorting the frequencies takes \( O(k \log k) \), where \( k \) is the number of unique characters. In the worst case, \( k \) can be 26 for lowercase English letters.

  • Calculating Total Pushes:

    Iterating through the sorted frequencies to calculate the total pushes takes \( O(k) \).

  • Overall Time Complexity:

    The overall time complexity is \( O(n + k \log k) \). Since \( k \leq 26 \), the time complexity is effectively \( O(n) \).

Space Complexity

  • Set and Map Storage:

    Storing unique characters in a set and character frequencies in an unordered map takes \( O(k) \) space, where \( k \) is the number of unique characters.

  • Additional Storage:

    We use additional space to store the sorted frequencies, which also takes \( O(k) \) space.

  • Overall Space Complexity:

    The overall space complexity is \( O(k) \), where \( k \leq 26 \). Thus, it is effectively \( O(1) \) in terms of the input string size.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top