Problem 2129

Abstract / Summary

Given a title string, convert the first character of each word to uppercase and the rest to lowercase.

Note

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

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)
10 lines | 292 bytes | submitted January 28, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (100k+ 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 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.

written by openai gpt

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.

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 = 8 | μ = 7.67 | σ = 0.77

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++ 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
24 links | 12 authors | 8 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   January 28, 2024

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