Skip to main content

520. Detect Capital

easy

Decide whether a word follows one of three capitalisation rules. A clean one-liner if you know the right library predicate, and a great chance to talk about character classification.

By Sam K., Founder, InterviewChamp.AI · Last verified

Problem

We define the usage of capitals in a word to be right when one of the following cases holds: (1) all letters in this word are capitals, like 'USA'; (2) all letters in this word are not capitals, like 'leetcode'; or (3) only the first letter in this word is capital, like 'Google'. Given a string word, return true if the usage of capitals in it is right.

Constraints

  • 1 <= word.length <= 100
  • word consists of lowercase and uppercase English letters.

Examples

Example 1

Input
word = "USA"
Output
true

Explanation: All letters are capitals — rule 1.

Example 2

Input
word = "FlaG"
Output
false

Explanation: Mixed case after the first letter violates all three rules.

Example 3

Input
word = "Google"
Output
true

Explanation: Only the first letter is capital — rule 3.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Three valid shapes: ALL_UPPER, all_lower, Title.

Hint 2

Count uppercase letters. If the count is 0 (all lower) or equals len(word) (all upper) it is valid.

Hint 3

Otherwise valid only when count == 1 AND the uppercase letter is at index 0.

Solution approach

Reveal approach

Count the number of uppercase letters in the word. Three valid cases: count == 0 (all lowercase), count == len(word) (all uppercase), or count == 1 and word[0] is uppercase (title case). Anything else fails. O(n) time and O(1) extra space. Idiomatic Python uses word.isupper() or word.islower() or word.istitle() chained with or — fine to mention but worth showing the manual approach too.

Complexity

Time
O(n)
Space
O(1)

Related patterns

  • string-classification
  • counting

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Google
  • Amazon

More Strings practice problems

See all Strings problems →