Valid Word Solution in Python

Problem Description

Ah, the classic “Valid Word” problem! It’s like trying to figure out if your friend’s text message is actually a word or just a random collection of letters that even a toddler would struggle to pronounce. The task is to determine if a given string (or word) is valid based on a few simple rules.

In the world of LeetCode, a valid word must:

  • Be at least 3 characters long.
  • Contain at least one vowel (because, let’s face it, no one wants to read a word that sounds like a sneeze).
  • Contain at least one consonant (because vowels alone can’t hold a conversation).

So, if you’ve ever received a text that reads “brr” or “aaa,” you know the struggle.

Code Solution


class Solution:
    def isValid(self, word: str) -> bool:
        kVowels = 'aeiouAEIOU'

        def isConsonant(c: str) -> bool:
            return c.isalpha() and c not in kVowels

        return (len(word) >= 3 and
                all(c.isalnum() for c in word) and
                any(c in kVowels for c in word) and
                any(isConsonant(c) for c in word))

Approach

The approach taken in this code is straightforward yet effective. It checks the following:

  • The length of the word is at least 3 characters.
  • All characters in the word are alphanumeric (because we don’t want any special characters crashing the party).
  • There is at least one vowel present.
  • There is at least one consonant present.

If all these conditions are met, the word is deemed valid. It’s like a bouncer at a club checking IDs and making sure everyone is dressed appropriately!

Time and Space Complexity

Time Complexity

O(n), where n is the length of the word. This is because we are iterating through the characters of the word multiple times.

Space Complexity

O(1), as we are using a constant amount of space regardless of the input size.

Real-World Example

Imagine you’re at a party, and someone walks in with a name tag that says “aaa.” You’d probably raise an eyebrow and wonder if they were just trying to get attention or if they were actually a person. Similarly, the “Valid Word” solution helps us filter out those awkward name tags (or words) that just don’t cut it.

Similar Problems

2-Sum Solution in Python