LeetCode 2266: Count Number of Texts Solution

Master LeetCode problem 2266 (Count Number of Texts), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2266. Count Number of Texts

Problem Explanation

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.

Solution Code

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);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2266 (Count Number of Texts)?

This page provides optimized solutions for LeetCode problem 2266 (Count Number of Texts) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2266 (Count Number of Texts)?

The time complexity for LeetCode 2266 (Count Number of Texts) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2266 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2266 in Java, C++, or Python.

Back to LeetCode Solutions