We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Valid Word

Number: 3396

Difficulty: Easy

Paid? No

Companies: Expedia


Problem Description

Given a string word, determine if it is a valid word. A valid word must have a minimum length of 3, consist solely of digits and English letters (both uppercase and lowercase), and must contain at least one vowel and at least one consonant (for letters only). If the word meets all conditions, return true; otherwise, return false.


Key Insights

  • Check the length of the word; if less than 3, it's immediately invalid.
  • Ensure every character is either a digit or an English letter.
  • To validate vowels and consonants, iterate over each letter and use a set for vowels.
  • For letters, if it is not a vowel, it is a consonant.
  • Digits do not affect vowel/consonant conditions but are allowed in the word.

Space and Time Complexity

Time Complexity: O(n) where n is the number of characters in the word.
Space Complexity: O(1) constant space usage.


Solution

The approach iterates through the input string once. During the iteration, it validates that each character is either a digit or a letter. For letters, the solution determines if the character is a vowel (using a predefined set of vowels) or a consonant. The function tracks the presence of at least one vowel and one consonant. If the word's length is less than 3 or if it contains invalid characters, the solution returns false. Otherwise, based on the tracked vowel and consonant, it returns whether the word is valid. The main data structures used are a set (or hash set) for vowels and simple boolean flags to capture required conditions.


Code Solutions

# Function to check if word is valid
def is_valid_word(word):
    # Check if the word has at least 3 characters
    if len(word) < 3:
        return False
    
    vowels = set("aeiouAEIOU")  # Set of valid vowel characters
    has_vowel = False  # Flag to indicate if word contains at least one vowel
    has_consonant = False  # Flag to indicate if word contains at least one consonant

    # Iterate through each character in the word
    for char in word:
        # Check if character is a digit or an alphabet letter
        if not (char.isdigit() or char.isalpha()):
            return False  # Invalid character found

        # Process letters to check for vowel and consonant
        if char.isalpha():
            if char in vowels:
                has_vowel = True  # Letter is a vowel
            else:
                has_consonant = True  # Letter is a consonant

    # Return true only if both a vowel and a consonant have been found
    return has_vowel and has_consonant

# Example test runs
print(is_valid_word("234Adas"))  # Expected output: True
print(is_valid_word("b3"))       # Expected output: False
print(is_valid_word("a3$e"))      # Expected output: False
← Back to All Questions