3136. Valid Word
Problem Description
A word is considered valid if it meets the following criteria:
- It contains a minimum of 3 characters.
- It consists only of digits (0-9) and English letters (both 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:
- The letters 'a', 'e', 'i', 'o', 'u', and their uppercase variants are considered vowels.
- A consonant is any English letter that is not a vowel.
Intuition
To determine if a word is valid, we address the following tasks systematically:
-
Length Check: First, we assess if the length of the
word
is less than 3. If it is, it doesn't satisfy the minimum length requirement and thus returnsfalse
. -
Character Validation: We then iterate through each character to ensure they are either digits or letters. This ensures the word only consists of alphanumeric characters. If a non-alphanumeric character is found, the function returns
false
. -
Vowel and Consonant Check: During the iteration through the string, we check if there's at least one vowel and one consonant. We use two flags,
has_vowel
andhas_consonant
, which are toggled totrue
upon finding their respective character types. For vowels, we use a predefined set of vowel characters for quick lookup. -
Final Validation: After completing the iteration, we confirm that both the
has_vowel
andhas_consonant
flags are true. If both are true, the word meets all requirements and is deemed valid, returningtrue
. Otherwise, it returnsfalse
.
This approach ensures all the criteria for a valid word are checked efficiently by leveraging condition checks and flags in a single traversal of the string.
Solution Approach
Solution 1: Simulation
The solution uses a straightforward simulation approach to check if the given word meets all the criteria for validity.
-
Initial Length Check:
- First, the function checks if the length of the string
word
is less than 3. If this is the case, the function immediately returnsFalse
because the word doesn't have enough characters to be valid.
- First, the function checks if the length of the string
-
Variable Setup:
- Two boolean variables are initialized:
has_vowel
andhas_consonant
, both set initially toFalse
. - A set
vs
is created to store all vowels for quick membership checking:set("aeiouAEIOU")
.
- Two boolean variables are initialized:
-
Character Iteration:
- The function iterates over each character
c
in theword
. - For each character:
- Alphanumeric Check:
- It checks whether
c
is alphanumeric usingc.isalnum()
. Ifc
is not a letter or digit, the function returnsFalse
, as the word contains invalid characters.
- It checks whether
- Vowel Check:
- It checks if
c
is a vowel by verifying if it is in the setvs
. If so,has_vowel
is set toTrue
.
- It checks if
- Consonant Check:
- If
c
is alphabetic but not a vowel, then it is a consonant, andhas_consonant
is set toTrue
.
- If
- Alphanumeric Check:
- The function iterates over each character
-
Final Validation:
- After the loop, the function checks if both
has_vowel
andhas_consonant
areTrue
. If they are, it means the word contains at least one vowel and one consonant, returningTrue
. - If either is
False
, the function returnsFalse
because the word does not satisfy all the necessary criteria.
- After the loop, the function checks if both
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through an example to see how the solution approach works. Consider the word apple
.
Step-by-Step Analysis:
-
Initial Length Check:
- The word
apple
has 5 characters, which is greater than the minimum requirement of 3. Thus, we proceed with further checks.
- The word
-
Variable Setup:
- Initialize
has_vowel
asFalse
. - Initialize
has_consonant
asFalse
. - Set
vs
as{"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
for quick vowel checking.
- Initialize
-
Character Iteration:
- First character (
a
):- It is alphanumeric and a vowel.
- Set
has_vowel
toTrue
.
- Second character (
p
):- It is alphanumeric and a consonant (not in
vs
). - Set
has_consonant
toTrue
.
- It is alphanumeric and a consonant (not in
- Third character (
p
):- It is alphanumeric and a consonant.
has_consonant
remainsTrue
.
- Fourth character (
l
):- It is alphanumeric and a consonant.
has_consonant
remainsTrue
.
- Fifth character (
e
):- It is alphanumeric and a vowel.
has_vowel
remainsTrue
.
- First character (
-
Final Validation:
- After processing all characters, both
has_vowel
andhas_consonant
flags areTrue
. - Since all criteria are met, the function returns
True
, confirming thatapple
is a valid word.
- After processing all characters, both
Solution Implementation
1class Solution:
2 def isValid(self, word: str) -> bool:
3 # If the word contains less than 3 characters, it cannot be valid.
4 if len(word) < 3:
5 return False
6
7 # Flags to check if the word contains at least one vowel and one consonant.
8 has_vowel = False
9 has_consonant = False
10
11 # Set of vowels for quick lookup.
12 vowels_set = set("aeiouAEIOU")
13
14 # Iterate over each character in the word.
15 for char in word:
16 # If the character is not alphanumeric, the word is invalid.
17 if not char.isalnum():
18 return False
19
20 # Check if the character is an alphabet.
21 if char.isalpha():
22 # Check if it is a vowel.
23 if char in vowels_set:
24 has_vowel = True
25 else: # Otherwise, it must be a consonant.
26 has_consonant = True
27
28 # The word is valid if it contains at least one vowel and one consonant.
29 return has_vowel and has_consonant
30
1class Solution {
2 public boolean isValid(String word) {
3 // Return false if the word is too short
4 if (word.length() < 3) {
5 return false;
6 }
7
8 // Initialize flags to check for vowels and consonants
9 boolean hasVowel = false;
10 boolean hasConsonant = false;
11
12 // Create a boolean array to identify vowels: a, e, i, o, u
13 boolean[] isVowel = new boolean[26];
14 for (char c : "aeiou".toCharArray()) {
15 isVowel[c - 'a'] = true;
16 }
17
18 // Iterate through each character in the word
19 for (char c : word.toCharArray()) {
20 // Check if character is alphabetic
21 if (Character.isAlphabetic(c)) {
22 // Check if the character is a vowel
23 if (isVowel[Character.toLowerCase(c) - 'a']) {
24 hasVowel = true;
25 } else {
26 hasConsonant = true;
27 }
28 } else if (!Character.isDigit(c)) { // Non-alphanumeric character found
29 return false;
30 }
31 }
32
33 // Return true only if the word contains at least one vowel and one consonant
34 return hasVowel && hasConsonant;
35 }
36}
37
1#include <string>
2#include <cctype>
3
4class Solution {
5public:
6 // Function to check the validity of a given word
7 bool isValid(std::string word) {
8 // A valid word must have at least 3 characters
9 if (word.size() < 3) {
10 return false;
11 }
12
13 // Flags to check the presence of vowels and consonants
14 bool hasVowel = false;
15 bool hasConsonant = false;
16
17 // Boolean array to mark vowels
18 bool vowelStatus[26] = {false};
19 std::string vowels = "aeiou";
20
21 // Mark vowels in the boolean array
22 for (char c : vowels) {
23 vowelStatus[c - 'a'] = true;
24 }
25
26 // Iterate over each character in the word
27 for (char c : word) {
28 if (std::isalpha(c)) { // Check if the character is a letter
29 if (vowelStatus[std::tolower(c) - 'a']) {
30 hasVowel = true; // The letter is a vowel
31 } else {
32 hasConsonant = true; // The letter is a consonant
33 }
34 } else if (!std::isdigit(c)) { // Check if the character is not a digit (invalid character)
35 return false;
36 }
37 }
38
39 // Valid if both a vowel and a consonant are present
40 return hasVowel && hasConsonant;
41 }
42};
43
1// Function to check if the given word is valid according to specified conditions
2function isValid(word: string): boolean {
3 // A valid word must have at least 3 characters
4 if (word.length < 3) {
5 return false;
6 }
7
8 // Variables to keep track of the presence of vowels and consonants
9 let hasVowel = false;
10 let hasConsonant = false;
11
12 // Set of characters representing vowels, including both lowercase and uppercase
13 const vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
14
15 // Iterate through each character in the word
16 for (const char of word) {
17 // If any character is not alphanumeric, the word is invalid
18 if (!char.match(/[a-zA-Z0-9]/)) {
19 return false;
20 }
21
22 // Check if the character is a letter
23 if (/[a-zA-Z]/.test(char)) {
24 // Check if the letter is a vowel
25 if (vowels.has(char)) {
26 hasVowel = true;
27 } else {
28 // If not a vowel, it must be a consonant
29 hasConsonant = true;
30 }
31 }
32 }
33
34 // The word is valid if it contains at least one vowel and one consonant
35 return hasVowel && hasConsonant;
36}
37
Time and Space Complexity
The time complexity of the code is O(n)
where n
is the length of the input string word
. This is because the function iterates over each character of the string once to check if it contains both a vowel and a consonant.
The space complexity is O(1)
because the amount of space used by the algorithm does not depend on the size of the input. The additional space is constant as it uses a set for vowels and a few boolean variables to track state.
Learn more about how to find time and space complexity quickly.
What is the best way of checking if an element exists in a sorted array once in terms of time complexity? Select the best that applies.
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!