Valid Word

Gulshan KumarGulshan Kumar
2 min read

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.

LeetCode Problem - 3136

class Solution {
    // Method to check if a word is valid based on the presence of vowels and consonants
    public boolean isValid(String word) {
        // If the word length is less than 3, it's invalid
        if (word.length() < 3) {
            return false;
        }

        // Initialize counts for vowels and consonants
        int vowelCount = 0;
        int consonantCount = 0;

        // Iterate through each character of the word
        for (char ch : word.toCharArray()) {
            // If the character is not a letter or digit, the word is invalid
            if (!Character.isLetterOrDigit(ch)) {
                return false;
            }

            // If the character is a vowel, increment the vowel count
            if ("aeiouAEIOU".indexOf(ch) != -1) {
                vowelCount++;
            } 
            // If the character is a consonant, increment the consonant count
            else if ((ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') && "aeiouAEIOU".indexOf(ch) == -1) {
                consonantCount++;
            }
        }

        // The word is valid if it contains at least one vowel and one consonant
        return vowelCount > 0 && consonantCount > 0;
    }
}
0
Subscribe to my newsletter

Read articles from Gulshan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gulshan Kumar
Gulshan Kumar

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman. I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.