↓Skip to main content
  1. LeetCode/

LeetCode 3136: Valid Word

·2 mins· ·
LeetCode Easy String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2024-05-05

  • Submissions: Wrong Answer → Accepted → Wrong Answer → Accepted

Approach
#

Check the four conditions one by one (String Template 4): length >= 3, every character alphanumeric, at least one vowel (either case), and at least one consonant. A consonant is a letter that is not a vowel; digits do not count.

My Attempts
#

  • The first 2024 version treated every non-vowel character as a consonant, so digits counted: "a3E" has only vowels and a digit, so the answer is False; it returned True.
  • A 2025 rewrite tested vowels with w in "aeiou", missing uppercase vowels: "bEE" returned False instead of True. Using w.lower() passed.

Solution
#

class Solution:
    def isValid(self, word: str) -> bool:
        if len(word) < 3 or not all(c.isalnum() for c in word):
            return False
        vowels = set("aeiouAEIOU")
        has_vowel = any(c in vowels for c in word)
        has_consonant = any(c.isalpha() and c not in vowels for c in word)
        return has_vowel and has_consonant

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Digits are not consonants; check that the character is a letter.
  • Uppercase vowels are vowels too.

Interview Explanation
#

I check length at least 3 and all characters alphanumeric, then require a vowel and a consonant, where a consonant must be a non-vowel letter. Time O(n).

Related

LeetCode 1189: Maximum Number of Balloons
·2 mins
LeetCode Easy Hash-Table String Counting
LeetCode 1189 note: each letter supports count // needed balloons, with l and o needed twice; take the minimum
LeetCode 1078: Occurrences After Bigram
·1 min
LeetCode Easy String
LeetCode 1078 note: split into words and check every three consecutive words, collecting the third when the first two match
LeetCode 1047: Remove All Adjacent Duplicates In String
·1 min
LeetCode Easy String Stack
LeetCode 1047 note: if the stack top equals the current character both vanish, otherwise push it; after a removal the new top may cancel with the next character
LeetCode 1002: Find Common Characters
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 1002 note: count each word and intersect all Counters (minimum count per character), then expand
LeetCode 1021: Remove Outermost Parentheses
·1 min
LeetCode Easy String Stack Bracket-Sequences
LeetCode 1021 note: track depth instead of a stack; the ‘(’ raising depth from 0 to 1 and the ‘)’ lowering it from 1 to 0 are outermost, everything else stays
LeetCode 929: Unique Email Addresses
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 929 note: split at @, normalize only the local part (drop everything after +, remove dots), rejoin with the domain and collect in a set