Valid Word Problem
#3136
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 3136.
A word is considered valid if:
- It contains a minimum of 3 characters.
- It contains only digits (0-9), and English letters (uppercase and lowercase).
- It includes at least one vowel.
- It includes at least one consonant.
You are given a string word.
Return true if word is valid, otherwise, return false.
Notes:
'a','e','i','o','u', and their uppercases are vowels.- A consonant is an English letter that is not a vowel.
Example 1:
Input: word = "234Adas"
Output: true
Explanation:
This word satisfies the conditions.
Example 2:
Input: word = "b3"
Output: false
Explanation:
The length of this word is fewer than 3, and does not have a vowel.
Example 3:
Input: word = "a3$e"
Output: false
Explanation:
This word contains a '$' character and does not have a consonant.
Constraints:
1 <= word.length <= 20wordconsists of English uppercase and lowercase letters, digits,'@','#', and'$'.
Solution
Approach: Simulation
A word with fewer than 3 characters is invalid. Otherwise scan it: any character that is not a letter or digit makes it invalid; a letter is recorded as a vowel or a consonant. The word is valid when both a vowel and a consonant were seen.
Complexity: time O(n), space O(1).
class Solution:
def isValid(self, word: str) -> bool:
if len(word) < 3:
return False
has_vowel = has_consonant = False
vs = set("aeiouAEIOU")
for c in word:
if not c.isalnum():
return False
if c.isalpha():
if c in vs:
has_vowel = True
else:
has_consonant = True
return has_vowel and has_consonant