Reverse Words With Same Vowel Count Problem
#3775
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3775.
You are given a string s consisting of lowercase English words, each separated by a single space.
Determine how many vowels appear in the first word. Then, reverse each following word that has the same vowel count. Leave all remaining words unchanged.
Return the resulting string.
Vowels are 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: s = "cat and mice"
Output: "cat dna mice"
Explanation:
- The first word "cat" has 1 vowel.
- "and" has 1 vowel, so it is reversed to form "dna".
- "mice" has 2 vowels, so it remains unchanged.
- Thus, the resulting string is "cat dna mice".
Example 2:
Input: s = "book is nice"
Output: "book is ecin"
Explanation:
- The first word "book" has 2 vowels.
- "is" has 1 vowel, so it remains unchanged.
- "nice" has 2 vowels, so it is reversed to form "ecin".
- Thus, the resulting string is "book is ecin".
Example 3:
Input: s = "banana healthy"
Output: "banana healthy"
Explanation:
- The first word "banana" has 3 vowels.
- "healthy" has 2 vowels, so it remains unchanged.
- Thus, the resulting string is "banana healthy".
Constraints:
1 <= s.length <= 10^5sconsists of lowercase English letters and spaces.- Words in
sare separated by a single space. sdoes not contain leading or trailing spaces.
Solution
Approach: Simulation
Split the string into words and count the vowels in the first word. Go through the other words: whenever a word has the same number of vowels, reverse it. Join the words back with single spaces.
Complexity: time O(n), space O(n), where n is the length of s.
class Solution:
def reverseWords(self, s: str) -> str:
def calc(w: str) -> int:
return sum(c in "aeiou" for c in w)
words = s.split()
cnt = calc(words[0])
ans = [words[0]]
for w in words[1:]:
if calc(w) == cnt:
ans.append(w[::-1])
else:
ans.append(w)
return " ".join(ans)