Detect Capital (LeetCode 520): Solution and Explanation

Easy
String

Return true when a word uses capitals in one of three accepted ways: all capitals ("USA"), no capitals ("leetcode"), or only the first letter capitalised ("Google").

Intuition

All three accepted shapes can be told apart by one number: how many capitals the word has.

All capitals means the count equals the length. All lowercase means the count is zero. Title case means the count is one and that one capital is the first letter.

Any other count, or a single capital somewhere other than the front, breaks every rule.

Approach: Count the capitals

  1. Walk the word and count uppercase letters.
  2. Return capitals == n or capitals == 0 or capitals == 1 and word[0] is uppercase.

Step-by-step example

word = "FlaG"
  1. 'F' is a capital: capitals = 1. All lowercase is ruled out.
  2. 'l' is lowercase: all capitals is ruled out. Title case is still possible.
  3. 'a' is lowercase: nothing changes.
  4. 'G' is a capital: capitals = 2. A capital after the first letter rules out title case.
  5. capitals = 2 is neither 0 nor 4, and not 1, so the answer is false.

Code: Python, Java, C++

1class Solution:
2    def detectCapitalUse(self, word: str) -> bool:
3        capitals = 0
4        for ch in word:
5            if ch.isupper():
6                capitals += 1
7        return capitals == len(word) or capitals == 0 or (capitals == 1 and word[0].isupper())
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the word.

Space

O(1)

Only a counter.

Other approaches

Compare against case conversions (time O(n), space O(n))

Return word == word.upper() or word == word.lower() or word == word.capitalize(). Short, but builds three new strings.

Check the tail against the second letter (time O(n), space O(1))

If the first letter is lowercase, every other letter must be lowercase. Otherwise every letter from index 1 on must match the case of word[1].

Common mistakes

  • Accepting a single capital anywhere. "leetcodE" has one capital but it is not the first letter, so it is invalid.
  • Treating a one-letter word specially. Both "g" and "G" are valid, and the count check already handles them.
  • Using capitalize() style helpers in languages where they behave differently on non-letters. The input is letters only, but the count is clearer.

Frequently asked questions

Why is a single capital letter word valid?

"G" has capitals equal to its length, so it counts as all capitals. It also fits title case.

Can the loop stop early?

Yes. Once there are at least two capitals and a lowercase letter has been seen, no rule can hold, so you can return false. For words of at most 100 letters it rarely matters.