520. Detect Capital
easyDecide 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 <= 100word consists of lowercase and uppercase English letters.
Examples
Example 1
word = "USA"trueExplanation: All letters are capitals — rule 1.
Example 2
word = "FlaG"falseExplanation: Mixed case after the first letter violates all three rules.
Example 3
word = "Google"trueExplanation: Only the first letter is capital — rule 3.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
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
- 709. To Lower Case
- 125. Valid Palindrome
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
More Strings practice problems
- 3. Longest Substring Without Repeating Characters
- 5. Longest Palindromic Substring
- 6. Zigzag Conversion
- 14. Longest Common Prefix
- 20. Valid Parentheses
- 28. Find the Index of the First Occurrence in a String
- 49. Group Anagrams
- 58. Length of Last Word