Leetcode 2947: Count Beautiful Substrings I

grid47
grid47
Exploring patterns and algorithms
Jan 17, 2024 5 min read

You are given a string s and a positive integer k. A string is beautiful if it satisfies the conditions that the number of vowels equals the number of consonants, and the product of the number of vowels and consonants is divisible by k. Return the number of non-empty beautiful substrings in the string.
Problem
Approach
Steps
Complexity
Input: The input consists of a string s and a positive integer k.
Example: s = 'abec', k = 2
Constraints:
• 1 <= s.length <= 1000
• 1 <= k <= 1000
• s consists of only lowercase English letters.
Output: The output is the number of non-empty substrings of s that are beautiful.
Example: Output: 1
Constraints:
• The number of substrings is non-negative.
Goal: To find and return the number of beautiful substrings from the input string.
Steps:
• Iterate through all possible substrings of s.
• Count the vowels and consonants in each substring.
• Check if the number of vowels equals the number of consonants and if their product is divisible by k.
Goal: The string length and the integer k have upper bounds, ensuring efficiency for the solution.
Steps:
• The solution should run efficiently for strings with lengths up to 1000.
Assumptions:
• The input string will contain only lowercase English letters.
• The value of k will be positive and within the range [1, 1000].
Input: s = 'abec', k = 2
Explanation: The substring 'abec' is the only beautiful substring. It has 2 vowels ['a', 'e'] and 2 consonants ['b', 'c']. Since the product of the number of vowels and consonants (2 * 2 = 4) is divisible by 2, it is considered beautiful.

Input: s = 'aaee', k = 1
Explanation: The substrings 'aa' and 'ee' are beautiful because they both have equal numbers of vowels and consonants, and their product is divisible by 1.

Link to LeetCode Lab


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