A word uses capital letters correctly when it has one of three shapes: every letter is a capital, no letter is a capital, or only the very first letter is a capital.
You are given a string word made of English letters. Return true if it has one of those shapes, and false otherwise.
Example 1
Input: word = "KAYAK" Output: true Why: every letter is a capital
2 more examples and the constraints
Example 2
Input: word = "Tokyo" Output: true Why: only the first letter is a capital
Example 3
Input: word = "ToKyo" Output: false Why: the K in the middle breaks every shape
Constraints
- 1 ≤ word.length ≤ 100
- word contains only lowercase and uppercase English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Compare with the three shapesO(n)
- Count the capitalsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Letter reads for a 100-letter word | Verdict |
|---|---|---|---|
| Compare with the three shapes | O(n) | Passes; builds three copies | |
| Count the capitals | O(n) | Best; one pass, no copies |
n = the length of word.
Edge cases to test
- A single letter. Both "q" and "Q" are correct: one letter is all small or all capitals.
- One capital, not first. "berliN" has caps = 1, but the capital is at the end, so it is false.
- Almost all capitals. "MADRId" has 5 capitals out of 6, which matches no shape.
- Long words. At 100 letters the scan is still a single pass.
Common mistakes
- Returning true whenever caps is 1, without checking that the capital is the first letter.
- Checking only "first letter capital" and forgetting that the rest must then be small.
- Treating a one-letter word as a special case that returns false.
How to talk through it
- 1Clarify. Is the word only letters? Can it be a single letter?
- 2Restate the rules. All capitals, no capitals, or only the first letter capital.
- 3Give the direct check. Compare the word with its upper, lower and title-case copies.
- 4Count instead. The rules only depend on how many capitals there are and whether the first letter is one, so one counter is enough.
- 5Test out loud. Try "Q", "berliN" and "kYoto" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?