LeetCode 520: Detect Capital Solution

Master LeetCode problem 520 (Detect Capital), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

520. Detect Capital

Easy

Problem Explanation

Explanation

To solve this problem, we need to check if the usage of capitals in the given word is right according to the defined rules. We can achieve this by checking the following conditions:

  1. If all letters are capitals.
  2. If all letters are lowercase.
  3. If only the first letter is capital.

We can iterate through the characters of the word and count the number of uppercase characters and the position of the first uppercase character. Based on these counts, we can determine if the capital usage is right.

  • Time complexity: O(n) where n is the length of the input word.
  • Space complexity: O(1)

Solution Code

class Solution {
    public boolean detectCapitalUse(String word) {
        int n = word.length();
        int upperCount = 0;
        int firstUpperIndex = -1;
        
        for (int i = 0; i < n; i++) {
            char ch = word.charAt(i);
            if (Character.isUpperCase(ch)) {
                upperCount++;
                if (i == 0) {
                    firstUpperIndex = 0;
                }
            }
        }
        
        if (upperCount == n || upperCount == 0 || (upperCount == 1 && firstUpperIndex == 0)) {
            return true;
        }
        
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 520 (Detect Capital)?

This page provides optimized solutions for LeetCode problem 520 (Detect Capital) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 520 (Detect Capital)?

The time complexity for LeetCode 520 (Detect Capital) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 520 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 520 in Java, C++, or Python.

Back to LeetCode Solutions