Detect Capital - Problem

We define the usage of capitals in a word to be right when one of the following cases holds:

  • All letters in this word are capitals, like "USA"
  • All letters in this word are not capitals, like "leetcode"
  • 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.

Input & Output

Example 1 — Proper Case
$ Input: word = "Google"
Output: true
💡 Note: First letter 'G' is uppercase, remaining letters 'o', 'o', 'g', 'l', 'e' are lowercase. This matches the third valid pattern.
Example 2 — All Uppercase
$ Input: word = "USA"
Output: true
💡 Note: All letters 'U', 'S', 'A' are uppercase. This matches the first valid pattern.
Example 3 — Invalid Mixed Case
$ Input: word = "FlaG"
Output: false
💡 Note: Mixed case with 'F' and 'G' uppercase, 'l' and 'a' lowercase. This doesn't match any of the three valid patterns.

Constraints

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

Visualization

Tap to expand
Detect Capital - Single Pass Count INPUT word = "Google" G o o g l e 0 1 2 3 4 5 Uppercase Lowercase Valid Cases: 1. "USA" - All caps 2. "leetcode" - All lower 3. "Google" - First cap only word = "Google" ALGORITHM STEPS 1 Count Capitals Iterate and count uppercase G-upper, o-lower, o-lower g-lower, l-lower, e-lower capitals = 1 2 Check Conditions Validate against 3 rules 3 Rule Check caps == 0? NO (1 != 0) caps == len? NO (1 != 6) caps==1 AND first upper? YES! (1==1 AND G is upper) 4 Return Result Third condition matched true FINAL RESULT "Google" follows rule #3 All capitals? NO (1 != 6) All lowercase? NO (1 != 0) First cap only? OK (1 == 1) Output: true Valid capital usage (First letter capital only) Key Insight: Count uppercase letters in a single pass. Valid if: (1) count == length (all caps), (2) count == 0 (all lower), or (3) count == 1 AND first character is uppercase. Time: O(n), Space: O(1). TutorialsPoint - Detect Capital | Single Pass Count Approach
Asked in
Google 15 Microsoft 12
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen