Facebook Pixel

2129. Capitalize the Title

EasyString
Leetcode Link

Problem Description

You are given a string title that contains one or more words separated by single spaces. Each word consists only of English letters.

Your task is to capitalize the string according to these rules:

  • If a word has 1 or 2 letters, convert all letters in that word to lowercase
  • If a word has 3 or more letters, convert the first letter to uppercase and all remaining letters to lowercase

Return the modified string with all words capitalized according to these rules.

Example walkthrough:

  • Input: "capiTalIze tHe titLe"
  • Word 1: "capiTalIze" has 10 letters → becomes "Capitalize" (first letter uppercase, rest lowercase)
  • Word 2: "tHe" has 3 letters → becomes "The" (first letter uppercase, rest lowercase)
  • Word 3: "titLe" has 5 letters → becomes "Title" (first letter uppercase, rest lowercase)
  • Output: "Capitalize The Title"

Another example:

  • Input: "First i of thE maTRIX"
  • Word 1: "First" has 5 letters → becomes "First"
  • Word 2: "i" has 1 letter → becomes "i" (all lowercase)
  • Word 3: "of" has 2 letters → becomes "of" (all lowercase)
  • Word 4: "thE" has 3 letters → becomes "The"
  • Word 5: "maTRIX" has 6 letters → becomes "Matrix"
  • Output: "First i of The Matrix"
Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The problem asks us to process each word independently based on its length, which immediately suggests we need to:

  1. Break the string into individual words
  2. Apply the capitalization rule to each word
  3. Combine them back together

The key insight is recognizing that this is a straightforward transformation problem where each word's treatment depends solely on its own length. There's no dependency between words, so we can process them independently.

For each word, we have a simple decision tree:

  • Is the word length less than 3? → Make it all lowercase
  • Otherwise → Make the first letter uppercase and the rest lowercase

Python provides convenient built-in methods that map perfectly to our needs:

  • split() naturally breaks the string by spaces into a list of words
  • lower() converts an entire string to lowercase
  • capitalize() does exactly what we need for longer words - makes the first letter uppercase and the rest lowercase

The elegance of the solution comes from recognizing that we can use a list comprehension to apply this logic to all words in one line: [w.lower() if len(w) < 3 else w.capitalize() for w in title.split()]. This creates a new list with each word properly formatted.

Finally, " ".join() reconstructs the sentence by combining all the processed words with spaces between them, giving us our final answer.

The entire problem boils down to: split → transform each word based on length → join back together.

Solution Approach

The solution follows a simple simulation approach where we directly implement the problem's requirements step by step.

Step 1: Split the string into words

title.split()

This breaks the input string at each space character, giving us a list of individual words. For example, "capiTalIze tHe titLe" becomes ["capiTalIze", "tHe", "titLe"].

Step 2: Process each word based on its length We use a list comprehension to transform each word:

[w.lower() if len(w) < 3 else w.capitalize() for w in title.split()]

For each word w:

  • If len(w) < 3 (word has 1 or 2 letters): Apply w.lower() to convert the entire word to lowercase
  • Otherwise (word has 3 or more letters): Apply w.capitalize() which automatically converts the first letter to uppercase and all remaining letters to lowercase

Step 3: Join the words back together

" ".join(words)

This combines all the processed words with a single space between each word, reconstructing the complete string.

Complete Implementation:

class Solution:
    def capitalizeTitle(self, title: str) -> str:
        words = [w.lower() if len(w) < 3 else w.capitalize() for w in title.split()]
        return " ".join(words)

Time Complexity: O(n) where n is the length of the input string, as we need to process each character once.

Space Complexity: O(n) for storing the split words and the result string.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with a small example: "i lOve leetcode"

Step 1: Split the string into words

title.split()  # Results in: ["i", "lOve", "leetcode"]

Step 2: Process each word based on its length

We'll examine each word in our list comprehension:

  • Word 1: "i"

    • Length = 1 (which is < 3)
    • Apply w.lower(): "i""i"
  • Word 2: "lOve"

    • Length = 4 (which is ≥ 3)
    • Apply w.capitalize(): "lOve""Love"
  • Word 3: "leetcode"

    • Length = 8 (which is ≥ 3)
    • Apply w.capitalize(): "leetcode""Leetcode"

After the list comprehension:

words = ["i", "Love", "Leetcode"]

Step 3: Join the words back together

" ".join(words)  # Results in: "i Love Leetcode"

Final Output: "i Love Leetcode"

The entire process in one line would be:

return " ".join([w.lower() if len(w) < 3 else w.capitalize() for w in "i lOve leetcode".split()])

This demonstrates how the solution correctly handles:

  • Short words (1-2 letters) by making them entirely lowercase
  • Longer words (3+ letters) by capitalizing only the first letter

Solution Implementation

1class Solution:
2    def capitalizeTitle(self, title: str) -> str:
3        """
4        Capitalizes words in a title based on their length.
5        Words with length < 3 remain lowercase, others are capitalized.
6      
7        Args:
8            title: A string containing words separated by spaces
9          
10        Returns:
11            A string with words capitalized according to the rules
12        """
13        # Split the title into individual words
14        words = title.split()
15      
16        # Process each word based on its length
17        processed_words = []
18        for word in words:
19            if len(word) < 3:
20                # Words shorter than 3 characters stay lowercase
21                processed_words.append(word.lower())
22            else:
23                # Words with 3 or more characters get capitalized (first letter uppercase, rest lowercase)
24                processed_words.append(word.capitalize())
25      
26        # Join the processed words back into a single string with spaces
27        return " ".join(processed_words)
28
1class Solution {
2    public String capitalizeTitle(String title) {
3        // List to store processed words
4        List<String> processedWords = new ArrayList<>();
5      
6        // Split the title into individual words by space
7        String[] words = title.split(" ");
8      
9        // Process each word based on its length
10        for (String word : words) {
11            // Words with length less than 3 should be all lowercase
12            if (word.length() < 3) {
13                processedWords.add(word.toLowerCase());
14            } else {
15                // Words with length 3 or more should have first letter capitalized
16                // and remaining letters in lowercase
17                String capitalizedWord = word.substring(0, 1).toUpperCase() + 
18                                       word.substring(1).toLowerCase();
19                processedWords.add(capitalizedWord);
20            }
21        }
22      
23        // Join all processed words with space and return the result
24        return String.join(" ", processedWords);
25    }
26}
27
1class Solution {
2public:
3    string capitalizeTitle(string title) {
4        // Convert entire string to lowercase first
5        transform(title.begin(), title.end(), title.begin(), ::tolower);
6      
7        // Create string stream to parse words
8        istringstream stringStream(title);
9        string result;
10        string word;
11      
12        // Process each word from the input
13        while (stringStream >> word) {
14            // Capitalize first letter if word length is greater than 2
15            if (word.size() > 2) {
16                word[0] = toupper(word[0]);
17            }
18          
19            // Append processed word to result
20            result += word;
21            result += " ";
22        }
23      
24        // Remove trailing space
25        result.pop_back();
26      
27        return result;
28    }
29};
30
1/**
2 * Capitalizes words in a title based on their length.
3 * Words with less than 3 characters are converted to lowercase.
4 * Words with 3 or more characters have their first letter capitalized and the rest lowercase.
5 * 
6 * @param title - The input title string to be capitalized
7 * @returns The formatted title with appropriate capitalization
8 */
9function capitalizeTitle(title: string): string {
10    // Split the title into individual words by space delimiter
11    const words: string[] = title.split(' ');
12  
13    // Process each word based on its length
14    const capitalizedWords: string[] = words.map((word: string) => {
15        // Words shorter than 3 characters should be all lowercase
16        if (word.length < 3) {
17            return word.toLowerCase();
18        }
19      
20        // Words with 3 or more characters should have first letter uppercase, rest lowercase
21        const firstLetter: string = word.slice(0, 1).toUpperCase();
22        const remainingLetters: string = word.slice(1).toLowerCase();
23        return firstLetter + remainingLetters;
24    });
25  
26    // Join the processed words back into a single string with spaces
27    return capitalizedWords.join(' ');
28}
29

Time and Space Complexity

The time complexity is O(n), where n is the length of the string title. This is because:

  • title.split() traverses the entire string once to split it into words: O(n)
  • The list comprehension iterates through each word, and for each word performs:
    • len(w): O(1) for each word (assuming constant time length retrieval)
    • w.lower() or w.capitalize(): O(k) where k is the length of the word
    • Since the sum of all word lengths equals n, the total for all words is O(n)
  • " ".join(words) traverses all words to join them: O(n)

The space complexity is O(n), where n is the length of the string title. This is because:

  • The words list stores all the processed words, which together contain approximately n characters
  • The final joined string returned by " ".join(words) also requires O(n) space
  • The intermediate strings created during lower() and capitalize() operations also contribute to O(n) space in total

Learn more about how to find time and space complexity quickly.

Common Pitfalls

Pitfall 1: Misunderstanding the Length Threshold

A common mistake is incorrectly implementing the length condition. Some developers might write:

if len(word) <= 2:  # Wrong! Should be < 3
    processed_words.append(word.lower())

This error occurs because the problem states "1 or 2 letters" should be lowercase, which translates to len(word) < 3, not len(word) <= 2. While these are mathematically equivalent, confusion can arise when the problem statement says "3 or more letters" for capitalization - leading some to use >= 3 for one condition and then incorrectly use <= 2 instead of < 3.

Solution: Stick to a consistent comparison operator. Use either < 3 and >= 3, or <= 2 and > 2 throughout your code.

Pitfall 2: Manual Capitalization Implementation

Some developers attempt to manually handle capitalization:

if len(word) >= 3:
    result = word[0].upper() + word[1:].lower()  # Risky approach

This approach fails when dealing with edge cases like empty strings in the word list (though the problem guarantees non-empty words, defensive programming is good practice).

Solution: Use Python's built-in capitalize() method which handles all edge cases correctly and is more readable.

Pitfall 3: Not Handling Mixed Case Input

Developers might forget that input words can have mixed cases throughout:

# Incorrect assumption that only first letter needs adjustment
if len(word) >= 3:
    result = word[0].upper() + word[1:]  # Wrong! Doesn't lowercase the rest

For input like "tHE", this would produce "THE" instead of the correct "The".

Solution: Always ensure you're converting all non-first letters to lowercase. The capitalize() method does this automatically, or explicitly use word[0].upper() + word[1:].lower().

Pitfall 4: Modifying During Iteration

Some might try to modify the list while iterating:

words = title.split()
for i, word in enumerate(words):
    words[i] = word.lower() if len(word) < 3 else word.capitalize()

While this works, it's less Pythonic and can lead to bugs if the logic becomes more complex.

Solution: Use list comprehension for cleaner, more functional code that creates a new list rather than modifying in place.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which technique can we use to find the middle of a linked list?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More