LeetCode 2266: Count Number of Texts

Problem Description

Explanation

To solve this problem, we can use dynamic programming. We iterate over the pressed keys and calculate the number of possible messages for each key based on the mappings provided. We maintain a dynamic programming array to store the number of possible messages for each key up to that point. The final answer will be the product of all the possibilities for each key. Finally, we return the answer modulo 10^9 + 7 to prevent overflow.

Algorithm:

  1. Initialize a dynamic programming array dp of size n+1, where n is the length of pressedKeys.
  2. Initialize dp[0] = 1 as there is only one way to form an empty message.
  3. Loop over i from 1 to n:
    • Initialize ways = 0.
    • For each possible mapping of the current key to letters, update ways by adding the number of ways to form the message ending with that letter.
    • Update dp[i] with the total number of ways up to the current key.
  4. Return dp[n] % (10^9 + 7) as the final answer.

Time Complexity: O(n), where n is the length of pressedKeys. Space Complexity: O(n), to store the dynamic programming array.

Solutions

class Solution {
    public int countNumber(String pressedKeys) {
        int mod = 1000000007;
        int n = pressedKeys.length();
        long[] dp = new long[n + 1];
        dp[0] = 1;
        
        for (int i = 1; i <= n; i++) {
            long ways = 0;
            for (int j = i; j >= 1 && i - j < 4; j--) {
                ways += dp[j - 1]; // Accumulate ways based on mappings
            }
            dp[i] = ways % mod;
        }
        
        return (int)(dp[n] % mod);
    }
}

Loading editor...