#3136

Valid Word

Easy
StringCharacter classificationSingle-pass validation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass through the string to check all conditions simultaneously. This reduces the number of iterations and checks, making it efficient.

⚙️

Algorithm

6 steps
  1. 1Step 1: Check if the length of the word is less than 3. If yes, return false.
  2. 2Step 2: Initialize flags for vowel and consonant presence.
  3. 3Step 3: Iterate through each character in the word and check its type in one go.
  4. 4Step 4: If a character is a letter, check if it's a vowel or consonant and update the flags.
  5. 5Step 5: If a character is not a digit or letter, return false immediately.
  6. 6Step 6: After the loop, return true if both flags are true; otherwise, return false.
solution.py13 lines
1def isValidWord(word):
2    if len(word) < 3:
3        return False
4    has_vowel = has_consonant = False
5    for char in word:
6        if char.isalpha():
7            if char.lower() in 'aeiou':
8                has_vowel = True
9            else:
10                has_consonant = True
11        elif not char.isdigit():
12            return False
13    return has_vowel and has_consonant

Complexity note: The time complexity is O(n) as we traverse the string once. The space complexity is O(1) since we only use a couple of boolean flags.

  • 1Understanding character types (vowels, consonants, digits) is crucial for this problem.
  • 2Checking conditions simultaneously can improve efficiency.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.