Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Number of Pushes to Type Word I solution and explanation

EasyGreedyMathString6 min read77.1% acceptanceUpdated 9 Apr 2026
Minimum Number of Pushes to Type Word I and II | Leetcode 3014 | Leetcode 3016 | Weekly ContestcodestorywithMIK · 31:28 · 9K viewsWatch on YouTube
9 more videos on this problem
  1. Minimum Number of Pushes to Type Word I and II | Leetcode 3014 | Leetcode 3016 | Weekly ContestcodestorywithMIK · 31:28 · 9K views
  2. 3014 Minimum Number of Pushes to Type Word I || Maths ✅ HashMap ❌Ayush Rao · 7:43 · 980 views
  3. 3014. Minimum Number of Pushes to Type Word I | 3016. Minimum Number of Pushes to Type Word IIcode Explainer · 10:03 · 564 views
  4. 3014. Minimum Number of Pushes to Type Word I (Leetcode Easy)Programming Live with Larry · 4:39 · 412 views
  5. 3014. Minimum Number of Pushes to Type Word I || Leetcode Weekly Contest 381Sanjay Prajapati · 9:56 · 399 views
  6. 3014. Minimum Number of Pushes to Type Word I #leetcodequestionandanswers #java #coding #coderCodeVia · 3:12 · 165 views
  7. Leetcode: 3014. Minimum Number of Pushes to Type Word IImran Sarwar · 14:58 · 164 views
  8. LeetCode 3014 Minimum Number of Pushes to Type a Word I | Python SolutionAI Learning Corner · 7:19 · 154 views
  9. Leetcode 3014 || Minimum Number of Pushes to Type Word I || Weekly Contest || EasyKomal Pal · 11:14 · 149 views
  10. Minimum Number of Pushes to Type Word I | Leetcode 3014 | Approach + Code with explanation.Pirai's Academy · 13:44 · 129 views

The 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.

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 = "xycdefghij"
Output: 12
Explanation: The remapped keypad given in the image provides the minimum cost.
"x" -> one push on key 2
"y" -> two pushes on key 2
"c" -> one push on key 3
"d" -> two pushes on key 3
"e" -> one push on key 4
"f" -> one push on key 5
"g" -> one push on key 6
"h" -> one push on key 7
"i" -> one push on key 8
"j" -> one push on key 9
Total cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12.
It can be shown that no other mapping can provide a lower cost.

Constraints:

  • 1 <= word.length <= 26
  • word consists of lowercase English letters.
  • All letters in word are distinct.

Approach overview

Problem Overview: You need to type a word using a phone keypad with 8 keys. Each key can contain multiple letters, and the number of pushes required equals the letter's position on its key (first letter = 1 push, second = 2 pushes, etc.). You can remap letters to any key. The goal is to assign letters so the total number of pushes needed to type the given word is minimized.

Approach 1: Greedy Mapping by Frequency (O(n + 26 log 26) time, O(1) space)

Count the frequency of each character in the word, then sort the frequencies in descending order. The key insight: letters used more often should require fewer pushes. Since there are 8 keys, the first 8 most frequent letters cost 1 push each, the next 8 cost 2, the next 8 cost 3, and the remaining letters cost 4. Iterate through the sorted frequencies and multiply each frequency by its push cost tier. This greedy assignment works because minimizing the push cost of high‑frequency letters always reduces the total operations. The algorithm mainly uses frequency counting from a string and a simple greedy ordering from greedy optimization principles.

Approach 2: Dynamic Partitioning Approach (O(26 * 26) time, O(26) space)

Another way to think about the problem is to decide how many letters should receive cost 1, 2, 3, and 4 pushes. With 8 keys available per level, the assignment becomes a partitioning problem across frequency values. Sort the character frequencies and evaluate partitions where the first group has cost 1, the next cost 2, and so on. A small dynamic programming or prefix-sum based evaluation can compute the minimal weighted cost across these partitions. Because the alphabet size is fixed (26), the computation remains constant time in practice. This perspective frames the problem as a cost minimization problem using simple arithmetic from math and frequency grouping.

Recommended for interviews: The greedy frequency mapping approach is what interviewers expect. It shows you recognize that higher-frequency characters should get cheaper operations. Counting frequencies and assigning push costs in sorted order is straightforward, optimal, and runs in linear time relative to the input length. Mentioning the partitioning perspective shows deeper understanding, but the greedy method demonstrates the strongest algorithmic intuition.

Approach 1: Greedy Mapping Approach

This approach involves using a greedy strategy where we try to distribute the letters across the available keys such that the number of key presses is minimized. Each key can have multiple letters mapped to it but typing a letter takes a number of pushes equivalent to its position in the key sequence. Start mapping from the letter requiring the most pushes to minimize push count overall.

def getMinimumPushes(word):
    word = sorted(word)
    minPushes = 0
    for i in range(len(word)):
        minPushes += (i // 9) + 1
    return minPushes

if __name__ == "__main__":
    word = "xycdefghij"
    print(getMinimumPushes(word))
import java.util.Arrays;

public class MinimumPushes {

    public static int getMinimumPushes(String word) {
        char[] letters = word.toCharArray();
        Arrays.sort(letters);
        int minPushes = 0;
        for (int i = 0; i < letters.length; i++) {
            minPushes += (i / 9) + 1;
        }
        return minPushes;
    }

    public static void main(String[] args) {
        String word = "xycdefghij";
        System.out.println(getMinimumPushes(word));
    }
}
#include <iostream>
#include <algorithm>
#include <string>

int getMinimumPushes(std::string word) {
    std::sort(word.begin(), word.end());
    int minPushes = 0;
    for (int i = 0; i < word.size(); i++) {
        minPushes += (i / 9) + 1;
    }
    return minPushes;
}

int main() {
    std::string word = "xycdefghij";
    std::cout << getMinimumPushes(word) << std::endl;
    return 0;
}
function getMinimumPushes(word) {
    let sortedWord = word.split('').sort().join('');
    let minPushes = 0;
    for (let i = 0; i < sortedWord.length; i++) {
        minPushes += Math.floor(i / 9) + 1;
    }
    return minPushes;
}

let word = "xycdefghij";
console.log(getMinimumPushes(word));
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    char first = *(const char *)a;
    char second = *(const char *)b;
    return first - second;
}

int getMinimumPushes(char* word) {
    int length = strlen(word);
    qsort(word, length, sizeof(char), compare);

    int minPushes = 0;
    for(int i = 0; i < length; i++) {
        minPushes += (i / 9) + 1;
    }
    return minPushes;
}

int main() {
    char word[] = "xycdefghij";
    printf("%d\n", getMinimumPushes(word));
    return 0;
}
using System;
using System.Linq;

public class MinimumPushes {
    public static int GetMinimumPushes(string word) {
        var letters = word.OrderBy(c => c).ToArray();
        int minPushes = 0;
        for (int i = 0; i < letters.Length; i++) {
            minPushes += (i / 9) + 1;
        }
        return minPushes;
    }

    public static void Main() {
        string word = "xycdefghij";
        Console.WriteLine(GetMinimumPushes(word));
    }
}

The Python solution involves sorting the letters and systematically assigning them to push levels (keys 1 to 9) to minimize the costs. It uses integer division to determine the number of presses needed for placement of each letter.

Complexity

Time Complexity: O(n log n) - Due to sorting.
Space Complexity: O(n) - Sorting creates a new list.

Try this approach in the editor

Approach 2: Dynamic Partitioning Approach

In this approach, we consider treating the distribution of letters to keys as a dynamic programming problem. The aim is to find subsets of letters that can be optimally packed into a series of 9-slot keys (since each key can host up to 9 letters with minimal pushes needed as explained earlier) with consideration to minimize excess steps due to larger partitioning of letters repeatedly.

def minPushes(word):
    n = len(word)
    dp = [float('inf')] * (n + 1)
    dp[0] = 0

    for i in range(n):
        for j in range(1, 10):
            if i + j <= n:
                dp[i + j] = min(dp[i + j], dp[i] + j)

    return dp[n]

if __name__ == "__main__":
    word = "abcde"
    print(minPushes(word))
import java.util.Arrays;

public class MinPushesDP {
    public static int minPushes(String word) {
        int n = word.length();
        int[] dp = new int[n + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 1; j <= 9 && i + j <= n; j++) {
                dp[i + j] = Math.min(dp[i + j], dp[i] + j);
            }
        }
        return dp[n];
    }

    public static void main(String[] args) {
        String word = "abcde";
        System.out.println(minPushes(word));
    }
}
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>

int minPushes(const std::string &word) {
    int n = word.length();
    std::vector<int> dp(n + 1, INT_MAX);
    dp[0] = 0;

    for (int i = 0; i < n; ++i) {
        for (int j = 1; j <= 9 && i + j <= n; ++j) {
            dp[i + j] = std::min(dp[i + j], dp[i] + j);
        }
    }
    return dp[n];
}

int main() {
    std::string word = "abcde";
    std::cout << minPushes(word) << std::endl;
    return 0;
}
function minPushes(word) {
    const n = word.length;
    const dp = new Array(n + 1).fill(Infinity);
    dp[0] = 0;

    for (let i = 0; i < n; i++) {
        for (let j = 1; j <= 9; j++) {
            if (i + j <= n) {
                dp[i + j] = Math.min(dp[i + j], dp[i] + j);
            }
        }
    }
    return dp[n];
}

const word = "abcde";
console.log(minPushes(word));
#include <stdio.h>
#include <string.h>
#include <limits.h>

int minPushes(const char *word) {
    int n = strlen(word);
    int dp[n + 1];
    for (int i = 0; i <= n; ++i) dp[i] = INT_MAX;
    dp[0] = 0;

    for (int i = 0; i < n; ++i) {
        for (int j = 1; j <= 9 && i + j <= n; ++j) {
            dp[i + j] = fmin(dp[i + j], dp[i] + j);
        }
    }
    return dp[n];
}

int main(void) {
    const char* word = "abcde";
    printf("%d\n", minPushes(word));
    return 0;
}
using System;

public class MinPushesDP {
    public static int MinPushes(string word) {
        int n = word.Length;
        int[] dp = new int[n + 1];
        Array.Fill(dp, int.MaxValue);
        dp[0] = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 1; j <= 9 && i + j <= n; j++) {
                dp[i + j] = Math.Min(dp[i + j], dp[i] + j);
            }
        }
        return dp[n];
    }

    public static void Main() {
        string word = "abcde";
        Console.WriteLine(MinPushes(word));
    }
}

Python's flexibility to execute dynamic programming allows for comprehensive segmentation examination per approach to reduce typing effort dynamically.

Complexity

Time Complexity: O(n * 9) - Boundary checks must cover multiple segments for min reachables.
Space Complexity: O(n) - Accounting for dynamic table array data storage.

Try this approach in the editor

Approach 3: Greedy Algorithm

We notice that all the letters in the string word are different. Therefore, we can greedily distribute the letters evenly across the 8 keys to minimize the number of key presses.

The time complexity is O(n / 8), where n is the length of the string word. The space complexity is O(1).

function minimumPushes(word: string): number {
    const n = word.length;
    let ans = 0;
    let k = 1;
    for (let i = 0; i < ((n / 8) | 0); ++i) {
        ans += k * 8;
        ++k;
    }
    ans += k * (n % 8);
    return ans;
}
func minimumPushes(word string) (ans int) {
	n := len(word)
	k := 1
	for i := 0; i < n/8; i++ {
		ans += k * 8
		k++
	}
	ans += k * (n % 8)
	return
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Greedy Mapping Approach

Time Complexity: O(n log n) - Due to sorting.
Space Complexity: O(n) - Sorting creates a new list.

Dynamic Partitioning Approach

Time Complexity: O(n * 9) - Boundary checks must cover multiple segments for min reachables.
Space Complexity: O(n) - Accounting for dynamic table array data storage.

Greedy Algorithm–

Complexity analysis

ApproachTimeSpaceWhen to Use
Greedy Mapping by FrequencyO(n + 26 log 26)O(1)Best general solution. Assign cheapest push counts to the most frequent letters.
Dynamic Partitioning ApproachO(26 * 26)O(26)Useful for reasoning about push-cost groups or exploring cost partitioning strategies.

Frequently asked questions

Is Minimum Number of Pushes to Type Word I easy or hard?

Minimum Number of Pushes to Type Word I is classified as an Easy problem. The main challenge is recognizing that assigning lower push costs to higher-frequency letters minimizes the total operations. Once that greedy insight is clear, the implementation is straightforward.

Minimum Number of Pushes to Type Word I Python/Java solution

Python and Java implementations follow the same idea: compute a frequency array for 26 letters, sort it in descending order, and assign push costs based on index groups of size eight. Each frequency is multiplied by its push cost tier and summed. The logic is short and runs in linear time relative to the input size.

How to solve Minimum Number of Pushes to Type Word I in O(n)?

Scan the word and count the frequency of each character. Sort the 26 frequencies in descending order and assign push costs based on position: the first 8 letters cost 1 push, the next 8 cost 2 pushes, the next 8 cost 3 pushes, and the remaining letters cost 4 pushes. Multiply each frequency by its assigned push cost and sum the results to get the minimum total pushes.

What is the best approach for Minimum Number of Pushes to Type Word I?

The greedy frequency assignment approach is the most efficient. Count how often each letter appears, sort the frequencies in descending order, and assign the smallest push counts to the most frequent letters. Because only 8 letters can have the same push cost tier, the first 8 get cost 1, the next 8 cost 2, and so on. This minimizes the total number of pushes required to type the word.

Is Minimum Number of Pushes to Type Word I asked at Google/Amazon/Meta?

Problems involving greedy frequency assignment and keypad optimization commonly appear in interviews at companies like Amazon, Google, and Meta. Variations of this question test your ability to minimize weighted costs using greedy ordering and frequency counting.

What data structure is used in Minimum Number of Pushes to Type Word I?

The main data structure is a frequency array or hash map to count occurrences of each letter. After counting, the frequencies are sorted to apply the greedy assignment of push costs. The algorithm also relies on simple array iteration and arithmetic calculations.

What is the time complexity of Minimum Number of Pushes to Type Word I?

The optimal solution runs in O(n + 26 log 26) time, where n is the length of the word. The algorithm scans the string once to compute character frequencies and then sorts at most 26 values. Space complexity is O(1) because the alphabet size is fixed.

Comments

Now write it yourselfClose this page and solve Minimum Number of Pushes to Type Word I in the editor, without looking.
Practise Minimum Number of Pushes to Type Word I