Count Number of Texts - Dynamic Programming [JS]

Description 

Solution: Dynamic Programming - Tabulation

The base case is dp[n] = 1.
dp[i] means the number of ways from i to n - 1.

Time Complexity: O(n)266ms
Space Complexity: O(n) 63.2MB

var countTexts = function(pressedKeys) {
  let n = pressedKeys.length, dp = Array(n + 1).fill(0);
  let four = new Set(['7', '9']), mod = 10 ** 9 + 7;
  dp[n] = 1; // base case
  
  for (let i = n - 1; i >= 0; i--) {
    for (let j = i + 1; j <= Math.min(n, i + 3); j++) {
      let substr = pressedKeys.slice(i, j);
      if (!hasOneUnique(substr)) break; // substring doesn't contain 1 unique digit
      dp[i] = (dp[i] + dp[j]) % mod;
    }
    
    if (i + 4 > n || !four.has(pressedKeys[i])) continue; // out of bounds or digit doesn't have four characters
    let substr = pressedKeys.slice(i, i + 4);
    if (hasOneUnique(substr)) { // substring contains 1 unique digit
      dp[i] = (dp[i] + dp[i + 4]) % mod;
    }
  }
  return dp[0];
  
  function hasOneUnique(str) {
    let unique = str[0];
    for (let char of str) {
      if (char !== unique) return false;
    }
    return true;
  }
};

javascript

Comments

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]