Capitalize the Title — LeetCode 2129 Python Solution

EasyString
Problem
#2129
Pattern
Hash Map
Reading time
2 min

The problem

You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: If the length of the word is 1 or 2 letters, change all letters to lowercase.

Example

Input
title = "capiTalIze tHe titLe"
Output
"Capitalize The Title"
Explanation
Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.

Python solution

Python
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)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the string `title` auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2129. Capitalize the Title is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2129. Capitalize the Title?
LeetCode 2129. Capitalize the Title is rated Easy on LeetCode.
What is the time complexity of LeetCode 2129. Capitalize the Title?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2129. Capitalize the Title?
The Python solution on this page uses O(n), where n is the length of the string `title` auxiliary space.
What topics does LeetCode 2129. Capitalize the Title cover?
LeetCode 2129. Capitalize the Title is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview