Skip to content
← All posts

Detect Capital: Counting Uppercase Letters

4 min read
leetcodeproblemeasystrings

LeetCode 520, Detect Capital, asks you to check whether a word uses capital letters correctly. There are exactly three valid patterns: all uppercase like "USA", all lowercase like "leetcode", or only the first letter uppercase like "Google". Anything else is invalid. If you have already solved Valid Anagram or Isomorphic Strings, you are comfortable with string traversal. This problem is simpler, but the counting technique it teaches is worth internalizing.

Three valid capitalization patternsAll upper:USAAll lower:leetcodeFirst upper:GoogleMixed:fLaGuppercaselowercasefirst upperinvalid
Capital usage is valid when all letters are uppercase, all are lowercase, or only the first letter is uppercase. Any other mix is invalid.

The problem

Given a string word, return True if the usage of capitals in it is correct.

Correct capital usage means one of these three conditions holds:

  1. All letters are uppercase: "USA" returns True
  2. All letters are lowercase: "leetcode" returns True
  3. Only the first letter is uppercase: "Google" returns True

Any other combination, like "fLaG" or "mIxEd", returns False.

The key insight

You do not need to check each pattern separately with complex conditionals. Instead, just count the uppercase letters. That single number tells you everything:

  • If the count is 0, every letter is lowercase. Valid.
  • If the count equals the length of the word, every letter is uppercase. Valid.
  • If the count is 1 and the first character is uppercase, only the first letter is capitalized. Valid.
  • Anything else is invalid.

One pass through the string, one counter, three checks.

The solution

def detectCapitalUse(word):
    upper_count = sum(1 for c in word if c.isupper())
    return upper_count == 0 or upper_count == len(word) or (upper_count == 1 and word[0].isupper())

That is the entire solution. Let's break it down:

  • Count uppercase letters. Walk through every character and count how many are uppercase. Python's isupper() method handles the check.
  • Check all lowercase. If upper_count == 0, there are no uppercase letters at all.
  • Check all uppercase. If upper_count == len(word), every single letter is uppercase.
  • Check title case. If upper_count == 1 and word[0].isupper(), the only uppercase letter is at the start.

The or short-circuits, so as soon as one condition is True, the function returns without checking the rest.

Step-by-step walkthrough

Failing example: word = "FLaG"

Step 1: Count uppercase letters in "FLaG"

upper_count = 3
FLaG

Scan each character. F is upper, L is upper, a is lower, G is upper. Total uppercase count = 3.

Step 2: Check all uppercase (count == len)?

upper_count = 3
FLaG

upper_count is 3 but len(word) is 4. Not all uppercase. This check fails.

3 != 4, skip

Step 3: Check all lowercase (count == 0)?

upper_count = 3
FLaG

upper_count is 3, not 0. Not all lowercase. This check fails.

3 != 0, skip

Step 4: Check first-letter-only (count == 1 and first is upper)?

upper_count = 3
FLaG

upper_count is 3, not 1. Not a single uppercase first letter. This check also fails.

3 != 1, skip

Step 5: No pattern matched. Return False.

upper_count = 3
FLaG

None of the three valid patterns matched. The capitalization of "FLaG" is incorrect.

False

Passing example: word = "Google"

Step 1: Count uppercase letters in "Google"

upper_count = 1
Google

Scan each character. Only G is uppercase. Total uppercase count = 1.

Step 2: Check all uppercase (count == len)?

upper_count = 1
Google

upper_count is 1 but len(word) is 6. Not all uppercase.

1 != 6, skip

Step 3: Check all lowercase (count == 0)?

upper_count = 1
Google

upper_count is 1, not 0. Not all lowercase.

1 != 0, skip

Step 4: Check first-letter-only (count == 1 and first is upper)?

upper_count = 1
Google

upper_count is 1, and word[0] is 'G' which is uppercase. This pattern matches!

True

Alternative: Python built-ins

Python has built-in string methods that map directly to the three patterns:

def detectCapitalUse(word):
    return word.isupper() or word.islower() or word.istitle()

isupper() returns True when all cased characters are uppercase. islower() returns True when all are lowercase. istitle() returns True when the first character of each word is uppercase and the rest are lowercase. Since the input is a single word with no spaces, istitle() checks exactly the "first letter only" pattern.

This is clean and readable, but the counting approach is more instructive. It teaches you to reduce a multi-condition problem to a single metric, a technique that transfers to harder problems.

Complexity analysis

ApproachTimeSpace
Count uppercaseO(n)O(1)
Python built-insO(n)O(1)

Both approaches scan the string once. No extra data structures are needed. The word length n is the only variable.

The building blocks

Counting with a predicate

The core technique here is scanning a collection and counting how many elements satisfy a condition. The template is:

count = sum(1 for item in collection if condition(item))

This micro-pattern appears in many string problems:

  • Detect Capital (this problem): count uppercase letters, then branch on the count
  • First Unique Character: count character frequencies, then find the first with count 1
  • Ransom Note: count available characters and verify the target is a subset
  • Valid Anagram: count character frequencies in two strings and compare

The key insight is that counting transforms a classification problem into a numeric comparison. Instead of writing nested if statements for each pattern, you extract a single metric and check it against known valid values.

Early reduction to a single metric

Many easy string problems can be solved by reducing the input to one number (a count, a length, an index) and then making decisions based on that number. Here you reduce the entire word to upper_count. This is the same mindset you use in Length of Last Word (reduce to a position) or Valid Anagram (reduce to frequency counts). Training yourself to ask "what single number captures what I need?" simplifies a lot of problems.

Edge cases

  • Single character. "A" is valid (all uppercase, and also qualifies as first-letter-only). "a" is valid (all lowercase). Both work correctly because upper_count is either 0 or 1 equaling len(word).
  • Two characters. "AB" is valid (all upper). "Ab" is valid (first upper, count is 1). "aB" is invalid (count is 1 but first char is lowercase). "ab" is valid (all lower).
  • All same letter. "aaaa" is valid. "AAAA" is valid. The count checks handle these naturally.
  • Length 1 edge. When the word has exactly one character, upper_count == len(word) and upper_count == 1 and word[0].isupper() both evaluate to the same thing. No special handling needed.

From understanding to recall

Detect Capital is rated easy, and the code is short. But the counting technique is the real prize here. Reducing a multi-pattern classification to a single count is a mental model that transfers to harder problems. Three weeks from now, when you face a problem that asks "does this string satisfy one of several structural patterns?", you want the instinct to count first and classify second.

Spaced repetition makes this automatic. You practice writing the counting solution from scratch at increasing intervals. After a few cycles, the pattern is in your fingers. When you see a capitalization or character-class problem, you already know to count and branch.

Related posts

  • Valid Anagram - Another easy string problem that reduces to counting character frequencies, the same "count and compare" mindset
  • Isomorphic Strings - Checking structural patterns in strings using hash maps, a step up in complexity from counting
  • Word Pattern - Verifying consistent mappings between sequences, another pattern-matching problem on strings