Problem 520

Abstract / Summary

Check if a word uses capital letters correctly according to title case rules.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0520.py

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        return len(word) == 1 or word.isupper() or word[1:].islower()
3 lines | 140 bytes | submitted September 9, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (700k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a single method, detectCapitalUse, that determines whether a given word follows the capitalization rules commonly expected in English: either all letters are uppercase, all letters are lowercase, or only the first letter is uppercase. The logic is expressed in a compact Boolean expression that leverages Python’s built-in string methods.

Key Steps

Length Check

The first part of the expression handles the situation where the word consists of a single character.

len(word) == 1

A single-letter word is considered valid regardless of its case, so the method returns True immediately for this scenario.

All-Uppercase Check

The second condition verifies whether the entire string is composed of uppercase letters.

word.isupper()

If every alphabetic character in word is uppercase, the method yields True.

First-Letter Uppercase Followed by Lowercase Check

The final condition examines the substring that starts from the second character onward, ensuring that the remainder of the word is entirely lowercase.

word[1:].islower()

When the first character may be uppercase (or lowercase) and the rest are all lowercase, the method also returns True.

The three conditions are combined with logical OR, so the method returns True if any one of them holds.

Edge Cases Handled

A word containing exactly one character is accepted without further inspection, covering inputs such as "A" or "z". When the word is composed solely of uppercase letters, for example "USA" or "HELLO", the isupper check validates the input. Words that start with an uppercase letter followed by only lowercase letters, such as "Google" or "Python", satisfy the slice-and-islower condition. All-lowercase words like "leetcode" also pass because the slice word[1:] is lowercase, and the first character being lowercase does not violate the rule. If the input string is empty, none of the conditions evaluate to True; the method consequently returns False, which aligns with the expectation that an empty word does not meet any capitalization rule. Non-alphabetic characters are implicitly addressed: methods isupper and islower return False when the string lacks cased characters, so a word such as "123" will be rejected unless it is a single character, in which case the length check grants acceptance.

Performance Optimizations

The implementation relies exclusively on Python’s native string methods (isupper, islower) and a simple length check. These built-in operations are executed in compiled C code, providing fast character classification without explicit Python loops. The use of short-circuit logical OR ensures that evaluation stops as soon as a true condition is found, avoiding unnecessary method calls. For instance, a single-character word bypasses both isupper and the slice operation. Slicing word[1:] creates a new string only when the earlier conditions have failed, minimizing memory allocation for the common cases where the word is either all uppercase or a single character.

Overall, the code delivers the required functionality with minimal computational overhead and a concise expression of the underlying rules.

written by openai gpt

ELI5 - Simplified Explanation

Think of this code like a helper that checks if a word is written with the right style. It looks at a word to see if people followed the rules for using capital letters. It first checks if the word is just a single letter, because a single letter is always allowed. If the word is longer, it checks if every single letter is big and tall like a giant. It also checks if the very first letter is big while all the other letters are small. If the word follows any of these patterns, the code says the word is good to go.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 8.81 | σ = 1.06

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fpdjsns C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fpdjsns C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
41 links | 28 authors | 10 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

4 medium 1 hard
6 solutions   September 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality