We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Detect Capital

Number: 520

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given a word, determine if the capitalization is used correctly. The word is correctly capitalized if either all letters are uppercase, all letters are lowercase, or only the first letter is uppercase and all other letters are lowercase.


Key Insights

  • Check three valid cases: all letters uppercase, all letters lowercase, or only the first letter uppercase.
  • A simple scan through the word or built-in string functions can determine the case of the characters.
  • Edge cases include single character strings where any capitalization is valid.

Space and Time Complexity

Time Complexity: O(n) where n is the length of the word (each character may need to be inspected) Space Complexity: O(1) (using a fixed number of extra variables)


Solution

The solution involves checking for three conditions:

  1. If the entire word is in uppercase.
  2. If the entire word is in lowercase.
  3. If the first character is uppercase and the remainder of the word is lowercase.

Data structures used: None, just basic string operations. Algorithmic approach: Use built-in string methods to evaluate the conditions. The solution leverages simple conditional checks to validate the word against the three correct capitalization patterns.


Code Solutions

# Python solution for checking capital usage in a word

def detectCapitalUse(word):
    # Check if all letters are uppercase
    if word.isupper():
        return True
    # Check if all letters are lowercase
    if word.islower():
        return True
    # Check if only the first letter is uppercase and the rest are lowercase
    if word[0].isupper() and word[1:].islower():
        return True
    return False

# Example usage:
print(detectCapitalUse("USA"))    # Expected output: True
print(detectCapitalUse("FlaG"))   # Expected output: False
← Back to All Questions