#2266
Count Number of Texts
MediumHash TableMathStringDynamic ProgrammingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to efficiently calculate the number of possible text messages by leveraging previously computed results, avoiding redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array where dp[i] represents the number of ways to decode the substring pressedKeys[0...i].
- 2Step 2: Iterate through the pressedKeys and for each digit, look back up to 4 positions (maximum length of the key) to calculate combinations based on the current digit.
- 3Step 3: Update the DP array based on the number of ways to form messages from previous indices.
solution.py18 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def countTexts(pressedKeys):
5 n = len(pressedKeys)
6 dp = [0] * (n + 1)
7 dp[0] = 1 # Base case
8
9 for i in range(1, n + 1):
10 count = 0
11 for j in range(1, 5): # Check up to 4 previous keys
12 if i - j >= 0 and pressedKeys[i - 1] == pressedKeys[i - j]:
13 count += dp[i - j]
14 count %= MOD
15 dp[i] = count
16
17 return dp[n]
18ℹ
Complexity note: The complexity is O(n) because we only iterate through the string once, and for each character, we check up to 4 previous characters, resulting in linear growth.
- 1The number of ways to form messages increases with consecutive identical digits.
- 2Dynamic programming helps in storing intermediate results to avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.