Python 2129.py
class Solution:
def capitalizeTitle(self, title: str) -> str:
words = []
for w in title.split(" "):
if len(w) > 2:
words.append(w.capitalize())
else:
words.append(w.lower())
return " ".join(words)
Difficulty
and has an acceptance rate of about 68% (100k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method capitalizeTitle. The method receives a string title and returns a transformed version where each word follows specific capitalization rules: words longer than two characters are capitalized (first letter uppercase, the rest lowercase), while shorter words are converted entirely to lowercase. The algorithm proceeds by splitting the input string on spaces, processing each token according to its length, collecting the results, and finally joining them back into a single string.
Key Steps
The first logical step isolates the individual words of the input. This is achieved with the split method, which separates the string wherever a space character occurs.
for w in title.split(" "):
Inside the loop, a conditional determines which transformation to apply based on the length of the current word. For words whose length exceeds two characters, the built-in capitalize method is invoked, which ensures the first character is uppercase and the remaining characters are lowercase.
if len(w) > 2:
words.append(w.capitalize())
For words of length two or less, the lower method is used to force all characters to lowercase.
else:
words.append(w.lower())
Each transformed word is appended to the list words. After the loop completes, the list contains the processed tokens in their original order. The final step concatenates the list back into a single string, inserting a single space between each element.
return " ".join(words)
Edge Cases Handled
The code implicitly addresses several edge conditions without explicit checks. When the input string contains consecutive spaces, split(" ") yields empty strings for the gaps, and those empty strings have a length of zero. The length check treats them as short words, and lower() on an empty string simply returns an empty string, preserving the original spacing pattern after the final join.
If the input consists solely of whitespace, the split operation produces a list of empty strings, and the join operation reconstructs a string of the same length of spaces, effectively returning the original whitespace unchanged.
Words that are already in the desired case are left untouched by the transformation methods because capitalize and lower are idempotent for correctly cased inputs. This includes single-character words, which are always converted to lowercase, matching the specification for short words.
The method also gracefully handles non-alphabetic characters within words. The capitalize method only affects alphabetic characters, leaving punctuation, digits, or symbols unchanged while still applying the case conversion to any alphabetic portion. Consequently, titles containing numbers or symbols are processed without raising errors.
Performance Optimizations
The implementation leverages Python’s built-in string methods, which are implemented in C and thus execute faster than equivalent Python-level loops. By using split and join, the code minimizes the number of intermediate string allocations; the list words is built once and then transformed into the final result in a single pass.
The conditional length check len(w) > 2 is a constant-time operation, allowing the method to decide the appropriate transformation without additional scanning of the word’s characters. This avoids unnecessary work for short words, as they bypass the more expensive capitalize routine.
Collecting transformed words in a list before joining avoids repeated string concatenation, which would otherwise lead to quadratic time behavior due to the immutable nature of Python strings. The final join call performs a single allocation for the output string, ensuring linear scaling with the total number of characters in the title.
ELI5 - Simplified Explanation
Imagine you have a long train made of many little word cars. This machine looks at each word car one by one to decide if it needs a new coat of paint. If a word car is very short, like having only one or two letters, the machine paints the whole thing in lowercase letters so it looks quiet and small. If a word car is longer than two letters, the machine gives it a special fancy capital letter at the front to make it stand tall and strong, while carefully painting the rest of its letters in lowercase. After all the word cars are checked and painted, the machine hooks them all back together with a single space between each one to form the finished title.
Code Quality
Complexity Analysis
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
Other Solutions
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++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | C# | Go | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 709: To Lower Case
Solved On The Same Day
- problem 2124: Check if All A's Appears Before All B's
- problem 2138: Divide a String Into Groups of Size k
- problem 2144: Minimum Cost of Buying Candies With Discount
- problem 2154: Keep Multiplying Found Values by Two
Extra
- 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