Leetcode 2266: Count Number of Texts

grid47
grid47
Exploring patterns and algorithms
Mar 25, 2024 7 min read

Alice is texting Bob using her phone’s keypad. Each digit from ‘2’ to ‘9’ maps to multiple letters, and Alice has to press a key several times to type each letter. However, due to a transmission error, Bob receives a string of digits corresponding to the number of key presses rather than the message itself. Your task is to determine how many possible messages Alice could have sent, given the sequence of digits Bob received. The answer should be returned modulo 1e9 + 7.
Problem
Approach
Steps
Complexity
Input: You are given a string `pressedKeys`, which contains digits from '2' to '9' representing the sequence of key presses Bob received.
Example: pressedKeys = '33322'
Constraints:
• 1 <= pressedKeys.length <= 10^5
• pressedKeys only contains digits from '2' to '9'.
Output: Return the number of possible messages that Alice could have sent, modulo 1e9 + 7.
Example: Output: 6
Constraints:
Goal: We need to determine the number of valid text messages that Alice could have sent based on the received sequence of key presses. The key insight is that consecutive identical digits represent the pressing of multiple letters corresponding to the digit's position on the keypad.
Steps:
• Use dynamic programming to keep track of the number of possible ways to decode the sequence of key presses.
• For each digit, check how many ways the preceding sequence could be decoded given the number of times the current digit is pressed.
• If multiple consecutive digits are the same, consider all possible letter combinations that could have been typed using those key presses.
Goal: The solution should work efficiently for large inputs with up to 10^5 key presses.
Steps:
• The solution must handle edge cases where a sequence of digits repeats multiple times.
Assumptions:
• The input string will only contain digits from '2' to '9'.
• The number of possible messages must be computed modulo 1e9 + 7.
Input: pressedKeys = '33322'
Explanation: The possible text messages Alice could have sent are: 'caa', 'cab', 'cbc', 'dda', 'ddb', 'dbc'. So the result is 6.

Input: pressedKeys = '555555'
Explanation: The possible text messages Alice could have sent are: 'kk', 'kl', 'lm', 'ln'. So the result is 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus