algoadvance

Leetcode 520. Detect Capital

Problem Statement

Leetcode 520: Detect Capital

Given a word, you need to determine if the usage of capital letters in it is right or not. The usage of capital letters is considered correct in the following cases:

Otherwise, return false.

Example 1:

Example 2:

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

Strategy

To solve this problem, we need to check the given word against the three valid capital usage patterns mentioned above:

  1. All letters in the word are uppercase.
  2. All letters in the word are lowercase.
  3. Only the first letter is uppercase and the rest are lowercase.

Using Java, this can be achieved by:

  1. Checking if the whole word is equal to its uppercase version.
  2. Checking if the whole word is equal to its lowercase version.
  3. Checking if the first character is uppercase and the rest of the word is lowercase.

Code

Here is the Java code to implement the solution:

class Solution {
    public boolean detectCapitalUse(String word) {
        // Case 1: All characters are uppercase
        if (word.equals(word.toUpperCase())) {
            return true;
        }
        
        // Case 2: All characters are lowercase
        if (word.equals(word.toLowerCase())) {
            return true;
        }
        
        // Case 3: Only the first character is uppercase and the rest are lowercase
        if (Character.isUpperCase(word.charAt(0)) && word.substring(1).equals(word.substring(1).toLowerCase())) {
            return true;
        }
        
        // If none of the cases match
        return false;
    }
}

Clarifying Questions

  1. Will the input always be a non-empty string?
  2. Can the input contain any non-alphabetic characters?

Time Complexity

The time complexity of this solution is O(n), where n is the length of the input string. This is due to performing at most three linear scans of the string:

  1. Converting the entire string to uppercase.
  2. Converting the entire string to lowercase.
  3. Checking that all but the first character are lowercase.

The space complexity is O(1) aside from the input and output, as no additional space proportional to the input size is used other than for auxiliary variables.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI