Capitalize the Title solution and explanation
9 more videos on this problem
Capitalize the Title || LeetCode 2129 || Biweekly LeetCode69 || LeetCode || String || ImplementationBro Coders · 6:59 · 2K views
2129. Capitalize the Title (Leetcode Problem: Biweekly Contest: 69)viralSongs · 2:58 · 1K views
Leetcode | 2129. Capitalize the Title | Easy | Java SolutionDeveloper Docs · 6:42 · 1K views
2129. Capitalize the Title (Leetcode Easy)Programming Live with Larry · 4:31 · 519 views
Can You Capitalize Titles With Code? (LeetCode 2129: Capitalize the Title)Code With Zi · 4:47 · 441 views
5960. Capitalize the Title (LeetcodeProblem)viralSongs · 1:20 · 410 views
Capitalize the Title - LeetCode 2129 - Java Solutionalgobest - Computer Science · 2:30 · 234 views
2129. Capitalize the Title with Python | Leetcode with Python #leetcode #pythontutorial #youtubeArsalan Ahmed · 11:33 · 200 views
2129. Capitalize the TitleLit Coder · 9:34 · 192 views
Capitalize The Title. Leetcode 2129 - masala.CodeWithAkbarov · 8:22 · 141 views
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
1or2letters, change all letters to lowercase. - Otherwise, change the first letter to uppercase and the remaining letters to lowercase.
Return the capitalized title.
Example 1:
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.
Example 2:
Input: title = "First leTTeR of EACH Word" Output: "First Letter of Each Word" Explanation: The word "of" has length 2, so it is all lowercase. The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.
Example 3:
Input: title = "i lOve leetcode" Output: "i Love Leetcode" Explanation: The word "i" has length 1, so it is lowercase. The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.
Constraints:
1 <= title.length <= 100titleconsists of words separated by a single space without any leading or trailing spaces.- Each word consists of uppercase and lowercase English letters and is non-empty.
Approach overview
Problem Overview: You receive a title string made of words separated by spaces. Words with length <= 2 must remain fully lowercase, while longer words must have the first letter uppercase and the rest lowercase. The task is straightforward string processing: scan each word, apply the rule, and rebuild the title.
Approach 1: String Traversal and Manipulation (O(n) time, O(n) space)
Split the title into words using spaces, then iterate through each word. For every word, check its length. If the length is <= 2, convert the entire word to lowercase using a built‑in function like lower(). Otherwise, capitalize the first character and lowercase the remaining characters using operations such as word[0].upper() and word[1:].lower(). Append the processed word to a result list and finally join the words with spaces to rebuild the string.
This approach relies on basic string manipulation operations and a single pass over the input. Each character is processed at most once, giving O(n) time where n is the length of the title. Because we store split words and rebuild the string, the extra memory cost is O(n). This is the most direct and readable solution and works consistently across languages like C++, Java, Python, and JavaScript.
Approach 2: Functional Programming (O(n) time, O(n) space)
Many languages support functional utilities such as map or list comprehensions. First split the title into words. Then apply a transformation function to each word: if its length is <= 2, return the lowercase version; otherwise return a new string with the first character uppercase and the rest lowercase. The map operation processes each word independently, and the results are joined with spaces at the end.
The key insight is treating the transformation as a pure function applied to every word. Languages like Python and JavaScript make this concise using list comprehensions or Array.map(). Complexity remains O(n) time and O(n) space since every character is visited once and a new string is constructed.
Recommended for interviews: The string traversal approach is what interviewers expect. It shows you can iterate through tokens, apply conditional logic, and rebuild strings efficiently. The functional style is elegant and concise but relies on language features rather than demonstrating step‑by‑step string processing logic. Showing the iterative solution first proves you understand the underlying mechanics.
Approach 1: String Traversal and Manipulation
This approach involves splitting the input string into individual words, iterating over each word to check its length, and then applying the capitalization rules accordingly. The words are then concatenated back into a single string.
def capitalize_title(title):
words = title.split()
result = []
for word in words:
if len(word) > 2:
result.append(word.capitalize()) # Capitalizes the first letter, lowercases others
else:
result.append(word.lower())
return " ".join(result)
# Example usage
print(capitalize_title("capiTalIze tHe titLe"))public class CapitalizeTitle {
public static String capitalizeTitle(String title) {
String[] words = title.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words) {
if (word.length() > 2) {
word = Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase();
} else {
word = word.toLowerCase();
}
if (result.length() > 0) {
result.append(" ");
}
result.append(word);
}
return result.toString();
}
public static void main(String[] args) {
String title = "capiTalIze tHe titLe";
System.out.println(capitalizeTitle(title));
}
}#include <iostream>
#include <sstream>
#include <cctype>
#include <string>
std::string capitalizeTitle(std::string title) {
std::istringstream iss(title);
std::string word, result;
while (iss >> word) {
if (word.length() > 2) {
word[0] = toupper(word[0]);
for (int i = 1; i < word.length(); ++i) {
word[i] = tolower(word[i]);
}
} else {
for (char& c : word) {
c = tolower(c);
}
}
if (!result.empty()) {
result += " ";
}
result += word;
}
return result;
}
int main() {
std::string title = "capiTalIze tHe titLe";
std::cout << capitalizeTitle(title) << std::endl;
return 0;
}function capitalizeTitle(title) {
return title.split(' ').map(word => {
return word.length > 2 ? word[0].toUpperCase() + word.slice(1).toLowerCase() : word.toLowerCase();
}).join(' ');
}
console.log(capitalizeTitle('capiTalIze tHe titLe'));#include <stdio.h>
#include <string.h>
#include <ctype.h>
void capitalizeTitle(char* title) {
char* token = strtok(title, " ");
while (token != NULL) {
if (strlen(token) > 2) {
token[0] = toupper(token[0]);
for (int i = 1; token[i]; i++) {
token[i] = tolower(token[i]);
}
} else {
for (int i = 0; token[i]; i++) {
token[i] = tolower(token[i]);
}
}
token = strtok(NULL, " ");
}
}
int main() {
char title[] = "capiTalIze tHe titLe";
capitalizeTitle(title);
printf("%s\n", title);
return 0;
}using System;
using System.Text;
class Program {
static string CapitalizeTitle(string title) {
string[] words = title.Split(' ');
StringBuilder result = new StringBuilder();
foreach (string word in words) {
if (word.Length > 2) {
result.Append(char.ToUpper(word[0]) + word.Substring(1).ToLower() + " ");
} else {
result.Append(word.ToLower() + " ");
}
}
return result.ToString().TrimEnd();
}
static void Main() {
string title = "capiTalIze tHe titLe";
Console.WriteLine(CapitalizeTitle(title));
}
}This Python solution splits the input string into words, processes each word in a loop, and then joins them back into a single string to return the result.
Time Complexity: O(n), where n is the number of characters in the string. Space Complexity: O(n), for storing the split words in a list.
Approach 2: Using Functional Programming (for supported languages)
This approach utilizes functional programming techniques, such as map and lambdas, to apply transformations directly on the array of words extracted from the input string.
def capitalize_title(title):
return ' '.join(map(lambda word: word.capitalize() if len(word) > 2 else word.lower(), title.split()))
# Example usage
print(capitalize_title("capiTalIze tHe titLe"))const capitalizeTitle = (title) => title.split(' ').map(word => word.length > 2 ? word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() : word.toLowerCase()).join(' ');
console.log(capitalizeTitle('capiTalIze tHe titLe'));This Python solution employs a functional style using map and a lambda function to capitalize words longer than two characters, achieved concisely in one line.
Time Complexity: O(n), where n is the number of characters in the string. Space Complexity: O(n), due to the intermediate list created.
Approach 3: Simulation
Directly simulate the process. Split the string by spaces to get each word, then convert each word to the appropriate case as per the problem statement. Finally, join the words with spaces.
The time complexity is O(n), and the space complexity is O(n), where n is the length of the string title.
function capitalizeTitle(title: string): string {
return title
.split(' ')
.map(s =>
s.length < 3 ? s.toLowerCase() : s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase(),
)
.join(' ');
}func capitalizeTitle(title string) string {
title = strings.ToLower(title)
words := strings.Split(title, " ")
for i, s := range words {
if len(s) > 2 {
words[i] = strings.Title(s)
}
}
return strings.Join(words, " ")
}Complexity comparison
| Approach | Complexity |
|---|---|
| String Traversal and Manipulation | Time Complexity: O(n), where n is the number of characters in the string. Space Complexity: O(n), for storing the split words in a list. |
| Using Functional Programming (for supported languages) | Time Complexity: O(n), where n is the number of characters in the string. Space Complexity: O(n), due to the intermediate list created. |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| String Traversal and Manipulation | O(n) | O(n) | Standard solution for interviews and most languages |
| Split and Rebuild with Functional Mapping | O(n) | O(n) | When using Python/JavaScript functional features for concise code |
Frequently asked questions
Is Capitalize the Title easy or hard?
Capitalize the Title is classified as an Easy problem on LeetCode with an acceptance rate around 68%. It focuses on basic string processing, conditional checks, and rebuilding strings rather than advanced algorithms.
Capitalize the Title Python/Java solution
In Python, you can split the string, transform each word using a loop or list comprehension, and join them with spaces. In Java, split the string using split(" "), process each word with substring and case conversion methods, then rebuild using StringBuilder or String.join(). Both implementations run in O(n) time.
How to solve Capitalize the Title in O(n)?
Split the string into words and iterate through them once. If a word length is less than or equal to 2, convert it entirely to lowercase. Otherwise capitalize the first letter and lowercase the rest. Join the processed words with spaces to produce the final title, giving O(n) time complexity.
What is the best approach for Capitalize the Title?
The best approach is simple string traversal. Split the title into words, check the length of each word, and apply lowercase or capitalization rules accordingly. This processes every character once and runs in O(n) time with O(n) extra space to rebuild the string.
Is Capitalize the Title asked at Google/Amazon/Meta?
This problem represents a common string manipulation pattern often seen in interviews at large tech companies. Variations of word formatting and capitalization logic frequently appear in screening rounds because they test careful handling of strings and edge cases.
What data structure is used in Capitalize the Title?
The problem mainly uses strings and arrays (or lists) of words. After splitting the title by spaces, each word is processed individually and stored in a list before joining back into a single string.
What is the time complexity of Capitalize the Title?
The optimal solution runs in O(n) time where n is the length of the title string. Each character is visited at most once during splitting, transformation, and reconstruction. Space complexity is O(n) because a new string or list of words is created.
