Similar Problems

Similar Problems not available

Count Vowel Strings In Ranges - Leetcode Solution

Companies:

LeetCode:  Count Vowel Strings In Ranges Leetcode Solution

Difficulty: Medium

Topics: string prefix-sum array  

Problem statement: Given four integers, namely, low, high, a, and b, we need to count the number of strings consisting of lowercase English letters such that in each string, the number of vowels is at least a and at most b (inclusive), and the total number of characters in the string is between low and high (inclusive).

Solution: We can solve this problem using dynamic programming. Let's define dp[i][j] as the number of strings of length i that end with the j-th vowel (where a=1 refers to 'a', a=2 refers to 'e', and so on). We can initialize dp[1][j]=1 as there is only one string of length 1 that ends with any vowel. We can then compute dp[i][j] as follows: for each vowel k such that k<=j (since we want the number of vowels in each string to be non-decreasing), we can add dp[i-1][k] to dp[i][j]. The final answer will be the sum of dp[i][j] for all i and j such that a<=j<=b and low<=i<=high.

Let's take an example to illustrate the above approach. Suppose low=1, high=2, a=1, and b=2. We can initialize dp[1][j]=1 for j=1 to 5. Then we can compute dp[2][j] as follows:

  • For j=1, we can add dp[1][1] and dp[1][2] to dp[2][1] as we can append 'a' or 'e' to any string of length 1 ending with 'a'.
  • For j=2, we can add dp[1][2], dp[1][3], and dp[1][4] to dp[2][2] as we can append 'e', 'i', or 'o' to any string of length 1 ending with 'e'.
  • For j=3, we can add dp[1][3], dp[1][4], and dp[1][5] to dp[2][3] as we can append 'i', 'o', or 'u' to any string of length 1 ending with 'i'.
  • For j=4, we can add dp[1][4] and dp[1][5] to dp[2][4] as we can append 'o' or 'u' to any string of length 1 ending with 'o'.
  • For j=5, we can add dp[1][5] to dp[2][5] as we can append 'u' to any string of length 1 ending with 'u'.

The final answer will be the sum of dp[i][j] for i=1 to 2 and j=a to b, which is dp[1][1]+dp[1][2]+dp[1][3]+dp[1][4]+dp[1][5]+dp[2][1]+dp[2][2]+dp[2][3]+dp[2][4]+dp[2][5]=1+1+1+1+1+3+3+3+2+1=17.

Time complexity: O((high-low+1)*(b-a+1))

  • There are (high-low+1) possible string lengths, and (b-a+1) possible number of vowels in each string.
  • For each combination of string length and number of vowels, we need to compute dp[i][j] for each i and j, which takes O(j)=O(1) time.
  • Therefore, the overall time complexity is O((high-low+1)*(b-a+1)).

Space complexity: O(high*(b-a+1))

  • We need to store dp[i][j] for each i and j.
  • The maximum value of i is high, and the maximum value of j-a is (b-a).
  • Therefore, the overall space complexity is O(high*(b-a+1)).

Conclusion: We can use dynamic programming to solve the Count Vowel Strings In Ranges problem in O((high-low+1)(b-a+1)) time and O(high(b-a+1)) space.

Count Vowel Strings In Ranges Solution Code

1