Skip to content

Problem 2: Chef and Happy Strings

Course: Intro Class - DSA - chapter 6

Problem Link: https://www.codechef.com/practice/course/strings/STRINGS/problems/HAPPYSTR

Chef has a string S with him. Chef is happy if the string contains a contiguous substring of length strictly greater than 2 in which all its characters are vowels.

Determine whether Chef is happy or not.

Note that, in english alphabet, vowels are a, e, i, o, and u.

Example 1:

Input: aeiou
Output: "Happy"
Explanation: "aei" is one contiguous substring with length strictly greater than 2 and only vowels

Example 2:

Input: abxy
Output: "Sad"
Explanation: There is no substring of length > 2 containing all vowels
Brute force

Generate all substrings with length > 2 and check if anyone of them is completely made of only vowels.

bool checkOnlyVowels(string s) {
// Returns true if only vowels in s, false otherwise
}
for(int i=0; i<n-2; i++) {
for(int j=i+2, j++) {
if (checkOnlyVowels(s.substr(i, j)) return true;
}
}
return false;
Optimisation

Observation: If a substring of length 4 or more has only vowels, then any substring of that substring of length 3 will also have only vowels. Thus, we can only focus on substrings of length 3.