Valid Word solution and explanation
9 more videos on this problem
Valid Word | Easy | Leetcode 3136 | codestorywithMIKcodestorywithMIK · 9:00 · 4K views
3136. Valid Word | C++ STL | tolower, toupper, isalpha, islower, isupper, isdigitAryan Mittal · 4:48 · 1K views
3136. Valid Word | Leetcode Daily - PythonLeetcode Daily · 4:14 · 863 views
3136. Valid Word (Leetcode Easy)Programming Live with Larry · 4:17 · 482 views
Daily Leetcode #1932: Jul 15, 2025 - 3136. Valid WordProgramming Live with Larry · 8:05 · 473 views
Valid Words | LeetCode 3136 | Java Code | Developer CoderDeveloper Coder · 8:20 · 358 views
Leetcode 3136: Valid Word | Python Easy Problem Solved Step-by-Step (Beginner Friendly)BugNoJutsu · 4:33 · 312 views
Leetcode 3136 | Valid Word 🔥 String + Clean Conditions | Fastest Logic Explained in 5 mins Study Placement · 5:10 · 246 views
Leetcode 3136 - Valid Word | Leetcode Daily Challenge | 15 July 2025 | Hindi ExplanationCode with Deepak · 6:13 · 211 views
3136. Valid Word | String | Greedy | LeetcodeRapid Syntax · 7:02 · 187 views
The problem
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 <= 20wordconsists of English uppercase and lowercase letters, digits,'@','#', and'$'.
Approach overview
Problem Overview: You receive a string word. A word is considered valid if it has length at least 3, contains only digits or English letters, and includes at least one vowel and one consonant. Digits are allowed but do not count toward vowel or consonant requirements. The task is to scan the string and verify these rules efficiently.
Approach 1: Iterative Character Check (O(n) time, O(1) space)
The direct solution walks through the string once and inspects each character. Use simple character checks: isalnum-style logic to ensure every character is a letter or digit. While iterating, maintain two boolean flags: one for detecting a vowel (a, e, i, o, u, case-insensitive) and another for detecting a consonant. Digits are ignored for these counters but still validated as allowed characters. If any character is neither a digit nor a letter, the word becomes invalid immediately. After the scan finishes, the word is valid only if both vowel and consonant flags are true.
This approach relies purely on linear iteration and constant state tracking. The algorithm touches each character exactly once, giving O(n) time complexity where n is the length of the string, and O(1) space since only a few flags are stored. This pattern appears frequently in string validation problems where constraints depend on character categories.
Approach 2: Optimized Early Exit (O(n) time, O(1) space)
This version follows the same core idea but exits as soon as the answer becomes impossible or confirmed. During iteration, immediately return false when encountering a non‑alphanumeric character. Track vowel and consonant presence the same way as before. The optimization comes from checking conditions during the scan: if invalid characters appear, terminate instantly instead of finishing the loop. In practice this reduces work for malformed inputs.
Although the worst‑case complexity remains O(n), early termination improves average performance when invalid characters occur near the beginning. The algorithm still uses constant memory, making it ideal for constrained environments. This pattern is common in input validation tasks across string processing and iteration-based problems.
Recommended for interviews: The expected solution is a single linear scan with character classification. Interviewers want to see that you validate constraints while iterating and maintain minimal state (vowel/consonant flags). A brute force multi-pass check would work but signals weaker problem structuring. The optimized single-pass approach demonstrates clean reasoning, correct use of string traversal, and attention to edge cases such as digits and special characters.
Approach 1: Iterative Character Check
In this method, we iterate through each character of the word to check for validity. We utilize flags to confirm the presence of at least one vowel and one consonant while ensuring all characters are either letters or digits. The function will early exit if conditions for a valid word are met within the iteration.
def is_valid_word(word: str) -> bool:
if len(word) < 3:
return False
has_vowel = has_consonant = False
for c in word:
if not c.isdigit() and not c.isalpha():
return False
if c in 'aeiouAEIOU':
has_vowel = True
elif c.isalpha():
has_consonant = True
if has_vowel and has_consonant:
return True
return Falsepublic class ValidWordChecker {
public static boolean isValidWord(String word) {
if (word.length() < 3) return false;
boolean hasVowel = false, hasConsonant = false;
for (char c : word.toCharArray()) {
if (!Character.isDigit(c) && !Character.isLetter(c)) return false;
if ("aeiouAEIOU".indexOf(c) != -1) hasVowel = true;
else if (Character.isLetter(c)) hasConsonant = true;
if (hasVowel && hasConsonant) return true;
}
return false;
}
}#include <iostream>
#include <cctype>
#include <string>
using namespace std;
bool isValidWord(const string& word) {
if (word.length() < 3) return false;
bool hasVowel = false, hasConsonant = false;
for (char c : word) {
if (!isdigit(c) && !isalpha(c)) return false;
if (string("aeiouAEIOU").find(c) != string::npos) hasVowel = true;
else if (isalpha(c)) hasConsonant = true;
if (hasVowel && hasConsonant) return true;
}
return false;
}function isValidWord(word) {
if (word.length < 3) return false;
let hasVowel = false;
let hasConsonant = false;
for (let char of word) {
if (!(/^[0-9a-zA-Z]$/.test(char))) return false;
if (/[aeiouAEIOU]/.test(char)) hasVowel = true;
else if (/[a-zA-Z]/.test(char)) hasConsonant = true;
if (hasVowel && hasConsonant) return true;
}
return false;
}#include <stdbool.h>
#include <ctype.h>
#include <string.h>
bool isValidWord(const char *word) {
if (strlen(word) < 3) return false;
bool hasVowel = false, hasConsonant = false;
for (int i = 0; word[i] != '\0'; i++) {
char c = word[i];
if (!isdigit(c) && !isalpha(c)) return false;
if (strchr("aeiouAEIOU", c)) hasVowel = true;
else if (isalpha(c)) hasConsonant = true;
if (hasVowel && hasConsonant) return true;
}
return false;
}public class WordValidator {
public static bool IsValidWord(string word) {
if (word.Length < 3) return false;
bool hasVowel = false, hasConsonant = false;
foreach (char c in word) {
if (!char.IsDigit(c) && !char.IsLetter(c)) return false;
if ("aeiouAEIOU".IndexOf(c) >= 0) hasVowel = true;
else if (char.IsLetter(c)) hasConsonant = true;
if (hasVowel && hasConsonant) return true;
}
return false;
}
}This Python function evaluates if a word is valid by leveraging built-in methods isdigit and isalpha to filter characters, and iterating through each to identify vowels and consonants. When both types of letters are found, the function confirms validity early.
Time Complexity: O(n), with n as word length.
Space Complexity: O(1), restricted to a small, constant space for logic flags.
Approach 2: Optimized Early Exit
This method enhances performance by exiting the loop as soon as the necessary conditions for a valid word are identified. By bundling multiple checks, this approach minimizes unnecessary operations and provides rapid results.
def is_valid_word(word: str) -> bool:
if len(word) < 3:
return False
has_vowel = has_consonant = False
i = 0
while i < len(word) and not (has_vowel and has_consonant):
c = word[i]
i += 1
if not c.isdigit() and not c.isalpha():
return False
if not has_vowel and c in 'aeiouAEIOU':
has_vowel = True
elif not has_consonant and c.isalpha() and c not in 'aeiouAEIOU':
has_consonant = True
return has_vowel and has_consonantpublic class ValidWordChecker {
public static boolean isValidWord(String word) {
if (word.length() < 3) return false;
boolean hasVowel = false, hasConsonant = false;
int i = 0;
while (i < word.length() && !(hasVowel && hasConsonant)) {
char c = word.charAt(i++);
if (!Character.isDigit(c) && !Character.isLetter(c)) return false;
if (!hasVowel && "aeiouAEIOU".indexOf(c) != -1) hasVowel = true;
if (!hasConsonant && Character.isLetter(c) && "aeiouAEIOU".indexOf(c) == -1) hasConsonant = true;
}
return hasVowel && hasConsonant;
}
}#include <iostream>
#include <cctype>
#include <string>
using namespace std;
bool isValidWord(const string& word) {
if (word.length() < 3) return false;
bool hasVowel = false, hasConsonant = false;
int i = 0;
while (i < word.length() && !(hasVowel && hasConsonant)) {
char c = word[i++];
if (!isdigit(c) && !isalpha(c)) return false;
if (!hasVowel && string("aeiouAEIOU").find(c) != string::npos) hasVowel = true;
if (!hasConsonant && isalpha(c) && string("aeiouAEIOU").find(c) == string::npos) hasConsonant = true;
}
return hasVowel && hasConsonant;
}function isValidWord(word) {
if (word.length < 3) return false;
let hasVowel = false;
let hasConsonant = false;
let i = 0;
while (i < word.length && !(hasVowel && hasConsonant)) {
let char = word[i++];
if (!(/^[0-9a-zA-Z]$/.test(char))) return false;
if (!hasVowel && /[aeiouAEIOU]/.test(char)) hasVowel = true;
else if (!hasConsonant && /[a-zA-Z]/.test(char) && !/[aeiouAEIOU]/.test(char)) hasConsonant = true;
}
return hasVowel && hasConsonant;
}#include <stdbool.h>
#include <ctype.h>
#include <string.h>
bool isValidWord(const char *word) {
if (strlen(word) < 3) return false;
bool hasVowel = false, hasConsonant = false;
int i = 0;
int length = strlen(word);
while (i < length && !(hasVowel && hasConsonant)) {
char c = word[i++];
if (!isdigit(c) && !isalpha(c)) return false;
if (!hasVowel && strchr("aeiouAEIOU", c)) hasVowel = true;
if (!hasConsonant && isalpha(c) && !strchr("aeiouAEIOU", c)) hasConsonant = true;
}
return hasVowel && hasConsonant;
}public class WordValidator {
public static bool IsValidWord(string word) {
if (word.Length < 3) return false;
bool hasVowel = false, hasConsonant = false;
int i = 0;
while (i < word.Length && !(hasVowel && hasConsonant)) {
char c = word[i++];
if (!char.IsDigit(c) && !char.IsLetter(c)) return false;
if (!hasVowel && "aeiouAEIOU".IndexOf(c) >= 0) hasVowel = true;
if (!hasConsonant && char.IsLetter(c) && "aeiouAEIOU".IndexOf(c) < 0) hasConsonant = true;
}
return hasVowel && hasConsonant;
}
}The Python function applies an efficient approach by bundling conditional checks to exit rapidly when the word confirms vowel and consonant existence.
Time Complexity: O(n), where exits might trigger earlier in certain cases.
Space Complexity: O(1), using negligible, constant additional space.
Approach 3: Simulation
First, we check if the length of the string is less than 3. If it is, we return false.
Next, we iterate through the string, checking if each character is a letter or a number. If it's not, we return false. Otherwise, we check if the character is a vowel. If it is, we set has_vowel to true. If it's not, we set has_consonant to true.
Finally, if both has_vowel and has_consonant are true, we return true. Otherwise, we return false.
The time complexity is O(n), and the space complexity is O(1). Where n is the length of the string.
function isValid(word: string): boolean {
if (word.length < 3) {
return false;
}
let hasVowel: boolean = false;
let hasConsonant: boolean = false;
const vowels: Set<string> = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
for (const c of word) {
if (!c.match(/[a-zA-Z0-9]/)) {
return false;
}
if (/[a-zA-Z]/.test(c)) {
if (vowels.has(c)) {
hasVowel = true;
} else {
hasConsonant = true;
}
}
}
return hasVowel && hasConsonant;
}func isValid(word string) bool {
if len(word) < 3 {
return false
}
hasVowel := false
hasConsonant := false
vs := make([]bool, 26)
for _, c := range "aeiou" {
vs[c-'a'] = true
}
for _, c := range word {
if unicode.IsLetter(c) {
if vs[unicode.ToLower(c)-'a'] {
hasVowel = true
} else {
hasConsonant = true
}
} else if !unicode.IsDigit(c) {
return false
}
}
return hasVowel && hasConsonant
}impl Solution {
pub fn is_valid(word: String) -> bool {
if word.len() < 3 {
return false;
}
let mut has_vowel = false;
let mut has_consonant = false;
let vowels = ['a', 'e', 'i', 'o', 'u'];
for c in word.chars() {
if !c.is_alphanumeric() {
return false;
}
if c.is_alphabetic() {
let lower_c = c.to_ascii_lowercase();
if vowels.contains(&lower_c) {
has_vowel = true;
} else {
has_consonant = true;
}
}
}
has_vowel && has_consonant
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Iterative Character Check | Time Complexity: O(n), with n as word length. Space Complexity: O(1), restricted to a small, constant space for logic flags. |
| Optimized Early Exit | Time Complexity: O(n), where exits might trigger earlier in certain cases. Space Complexity: O(1), using negligible, constant additional space. |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative Character Check | O(n) | O(1) | General case when validating characters and tracking vowel/consonant presence in a single pass |
| Optimized Early Exit | O(n) | O(1) | Preferred when invalid characters may appear early and you want immediate termination |
Frequently asked questions
Is Valid Word easy or hard?
Valid Word is categorized as an Easy problem. It focuses on straightforward string iteration and condition checks rather than advanced algorithms, making it a common warm-up for string validation questions.
Valid Word Python/Java solution
Python and Java implementations both follow the same pattern: loop through the characters, check alphanumeric validity, and update vowel or consonant flags. After the scan, confirm that the string length is at least three and that both flags are true.
How to solve Valid Word in O(n)?
Iterate through the string once and classify each character. Reject the word if any character is not a digit or English letter. Maintain two flags for vowel and consonant detection; after the loop, return true only if both are present and the length is at least three.
What is the best approach for Valid Word?
The best approach is a single-pass iterative scan of the string. Track whether at least one vowel and one consonant appear while ensuring every character is alphanumeric. This runs in O(n) time and O(1) space and cleanly handles all constraints in one traversal.
Is Valid Word asked at Google/Amazon/Meta?
Problems like Valid Word appear in screening rounds at companies such as Amazon and Google because they test careful input validation and string processing. The logic is simple but requires handling edge cases such as digits, uppercase letters, and invalid characters.
What data structure is used in Valid Word?
No complex data structure is required. The solution relies on basic string traversal with constant variables to track vowel and consonant presence. Some implementations use a small set or lookup string for vowels to simplify checks.
What is the time complexity of Valid Word?
The time complexity is O(n), where n is the length of the input string. Each character is inspected exactly once to verify whether it is a letter or digit and to track vowel and consonant presence. Space complexity stays O(1) because only a few boolean flags are used.
