Advertisement

Count the Number of Vowel Strings in Range - LeetCode 2586 Solution

Count the Number of Vowel Strings in Range - Complete Solution Guide

Count the Number of Vowel Strings in Range is LeetCode problem 2586, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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: words = ["are","amy","u"], left = 0, right = 2 Output: 2 Explanation: - "are" is a vowel string because it starts with 'a' and ends with '

Detailed Explanation

The problem asks you to count the number of strings within a given range of a larger array that meet a specific criterion. The criterion is that a string is considered a 'vowel string' if and only if it begins and ends with a vowel (a, e, i, o, u). The input consists of an array of strings (`words`), and two integers (`left`, `right`) representing the inclusive range of indices to consider within the `words` array. The output is a single integer representing the count of vowel strings within the specified range.

Solution Approach

The solution iterates through the `words` array from index `left` to `right` (inclusive). For each word, it checks if the first and last characters are vowels. If both are vowels, the `count` is incremented. Finally, the function returns the total `count` of vowel strings found within the specified range.

Step-by-Step Algorithm

  1. Step 1: Initialize a `count` variable to 0.
  2. Step 2: Iterate through the `words` array from index `left` to `right`.
  3. Step 3: For each word, extract the first and last characters.
  4. Step 4: Check if both the first and last characters are vowels (using a helper string or manual comparison).
  5. Step 5: If both are vowels, increment the `count`.
  6. Step 6: After iterating through all words in the range, return the final `count`.

Key Insights

  • Insight 1: The problem requires iterating through a subset of the input array. Focusing on only the specified range (`left` to `right`) is crucial for efficiency.
  • Insight 2: Efficiently checking if a character is a vowel is important. Using a string containing all vowels ('aeiou') and checking for membership using `in` (Python), `contains` (Java), `find` (C++), or manual comparison (C) is efficient.
  • Insight 3: The problem only requires examining the first and last characters of each word, making the process linear in the length of the examined words within the range.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Topics

This problem involves: Array, String, Counting.

Companies

Asked at: PayPal.