Count the Number of Vowel Strings in Range

You are given a 0-indexed array of string words and two integers left and right. A string is called a vowel string if it starts with a vowel character and ends with a vowel character where vowel characters are 'a', 'e', 'i', 'o', and 'u'. Return the number of vowel strings words[i] where i belongs to the inclusive range [left, right].


Example 1:
Input: String[] words = {"are", "amy", "u"}; left = 0, right = 2;
Output: 2

Algorithm:
  • Initialize a variable count to 0 to count the number of strings that meet the criteria.
  • Iterate over the words array from index left to index right (inclusive) using a for loop.
  • For each string in the array, check if its first and last characters are vowels using the isVowel method. If both the first and last characters are vowels, increment the count variable.
  • Return the final value of the count variable as the result of the function.

  • Code Implementation:
    class Main {
    public static int vowelStrings(String[] words, int left, int right) {
    int count = 0;
    for (int i = left; i <= right; i++) {
    if (isVowel(words[i].charAt(0)) && isVowel(words[i].charAt(words[i].length() - 1))) {
    count++;
    }
    }
    return count;
    }

    public static boolean isVowel(char c) {
    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') return true;
    return false;
    }

    public static void main(String[] args) {
    String[] words = {"are", "amy", "u"};
    int left = 0, right = 2;

    // printing answer
    System.out.println(vowelStrings(words, left, right));
    }
    }

    Output:

    2


    Complexity Analysis:

    Time Complexity: O(n), where n is the number of strings in the words array between indices left and right.

    Space Complexity: The space complexity is O(1) since the algorithm only uses a constant amount of additional memory.



    If you want to contribute such articles to solutions2coding.com please click here. Thank you!

    Previous Post Next Post

    Contact Form