Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
The rules combine a length check, a restriction on every character, and two existence checks. A single scan can validate the characters while remembering whether a vowel and a consonant have appeared.
Approach
Reject words shorter than three characters. Then inspect each character and reject immediately if it is not an ASCII digit or an uppercase or lowercase English letter. Mark the vowel flag for a, e, i, o, or u, in either case. Otherwise, mark the consonant flag if the character is not a digit.
Return true only when both flags are set. Digits are allowed but satisfy neither flag, and checking the allowed character set first prevents punctuation from being mistaken for a consonant. Uppercase and lowercase letters are treated consistently.
class Solution:
def isValid(self, word: str) -> bool:
if len(word) < 3:
return False
v, c = False, False
for x in word:
if not match('[0-9a-zA-Z]', x):
return False
if match('[aeiouAEIOU]', x):
v = True
elif not match('[0-9]', x):
c = True
return v and cComplexity analysis
Let n = word.length. Time: O(n). Auxiliary space: O(1).
