Taro Logo

Valid Word

#210 Most AskedEasy
Topics:
Strings

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 <= 20
  • word consists of English uppercase and lowercase letters, digits, '@', '#', and '$'.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the exact minimum length required for the word to be considered valid?
  2. Are uppercase letters considered, and should vowels and consonants be treated as case-insensitive (e.g., 'A' vs 'a')?
  3. Can the input string contain special characters, numbers, or spaces, and how should they be handled?
  4. What should be returned if the input string is empty or null?
  5. Are letters like 'y' or 'w' considered vowels or consonants for the purpose of this problem?

Brute Force Solution

Approach

Imagine you need to figure out if a given word meets a specific set of rules to be considered valid. The brute force approach involves looking at the word as a whole and individually checking every single rule against it one by one.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire word provided.
  2. Check the first rule to see if the word is long enough. If it is too short, stop right there and declare it invalid.
  3. Next, check every single character in the word to make sure it only consists of letters and numbers, completely ignoring any special symbols.
  4. Then, scan through all the characters again to ensure that at least one of them is a vowel.
  5. After that, scan through all the characters one more time to ensure that at least one of them is a consonant.
  6. If the word successfully passes every single one of these individual checks, conclude that the word is indeed valid.

Code Implementation

def is_valid(word):
    # We enforce a minimum length because short words lack enough structural complexity.
    if len(word) < 3:
        return False

    for character in word:
        if not character.isalnum():
            return False

    has_vowel_flag = False
    for character in word:
        if character.lower() in 'aeiou':
            has_vowel_flag = True
            
    # Vowels are mandatory to ensure the word contains pronounceable syllabic sounds.
    if not has_vowel_flag:
        return False

    has_consonant_flag = False
    for character in word:
        if character.isalpha() and character.lower() not in 'aeiou':
            has_consonant_flag = True
            
    # Consonants are necessary alongside vowels to form a complete valid word structure.
    if not has_consonant_flag:
        return False

    return True

Big(O) Analysis

Time Complexity
O(n) – Let n be the length of the given word. The algorithm first checks the length in constant time, then performs three separate sequential scans through the characters of the word to validate allowed characters, presence of at least one vowel, and presence of at least one consonant. Each of these checks iterates through the n characters of the word once. This results in approximately 3 * n total operations, which simplifies to the final Big O time complexity of O(n).
Space Complexity
O(1) – The algorithm only requires a few primitive tracking variables, such as boolean flags or counters, to monitor conditions like vowel and consonant presence during the character scans. Because these variables consume a constant amount of memory regardless of the word length N, no dynamic data structures or recursive call stacks are utilized. Consequently, the auxiliary space remains entirely constant as the input size grows.

Optimal Solution

Approach

To determine if a word is valid, we simply need to inspect it against a few basic rules regarding its length and the types of characters it contains. We can check these rules one by one to see if the word passes all of them.

Here's how the algorithm would work step-by-step:

  1. Check the total length of the word to ensure it is at least three characters long.
  2. Look at every individual letter and number in the word to make sure no forbidden symbols are present.
  3. Scan through the characters to guarantee that at least one vowel is hiding inside.
  4. Scan through the characters once more to guarantee that at least one consonant is also present.
  5. If the word satisfies every single one of these checks, declare it a valid word.

Code Implementation

def is_valid(word_to_check):
    # The minimum length constraint ensures words are not too short to be meaningful.
    if len(word_to_check) < 3:
        return False

    has_vowel = False
    has_consonant = False
    vowels_set = set("aeiouAEIOU")

    for character in word_to_check:
        if not character.isalnum():
            return False

        if character.isalpha():
            if character in vowels_set:
                has_vowel = True
            else:
                has_consonant = True

    # Both vowels and consonants are required to form a linguistically valid token.
    return has_vowel and has_consonant

Big(O) Analysis

Time Complexity
O(n) – Let n be the length of the word. Checking the length takes constant time, while iterating through the characters to validate allowed symbols, count vowels, and find consonants requires a single pass over the string. Because we inspect each of the n characters a constant number of times, the total operations scale linearly as 1 * n, which simplifies to O(n).
Space Complexity
O(1) – To determine if a word is valid, the algorithm only needs a few primitive scalar variables to keep track of counts and boolean flags for vowels and consonants. These variables use a constant amount of extra memory regardless of the input length. No dynamic data structures, temporary collections, or recursion stack frames are required. Therefore, the auxiliary space complexity remains strictly constant relative to the input size N.

Edge Cases

Empty or null string input
How to Handle:
Check for null or empty strings at the start and return false immediately.
String length is less than the minimum required character count
How to Handle:
Check the length of the string against the minimum constraint and return false if it falls short.
String contains only vowels with no consonants
How to Handle:
Maintain a boolean flag for consonants and return false if it remains unset after a full scan.
String contains only consonants with no vowels
How to Handle:
Maintain a boolean flag for vowels and return false if it remains unset after checking all characters.
String contains invalid characters such as punctuation or spaces
How to Handle:
Validate each character against an allowed set of alphanumeric characters and reject if any foreign symbol appears.
Mixed case letters for vowels and consonants
How to Handle:
Convert the entire string to lowercase during preprocessing to simplify vowel and consonant identification.
Extremely large string inputs
How to Handle:
Iterate through the string in a single linear pass with O(n) time complexity and O(1) space complexity to ensure optimal performance.
0/245 completed