2129. Capitalize the Title
Problem Description
The problem presents us with a string title
that includes one or more words, separated by a single space. Each word is made of English letters. Our task is to capitalize this string, but not in the conventional sense of making every first letter uppercase. Instead, we have to follow these specific rules:
- If a word is only one or two letters long, we must convert all its letters to lowercase.
- For words longer than two letters, we need to capitalize the first letter and make all the remaining letters lowercase.
The goal is to return the modified version of the title
string adhering to these capitalization rules.
Intuition
The solution leverages Python's built-in split
, lower
, and capitalize
string methods to transform the input title
following the stated rules. Here's the step-by-step approach:
- Split the input string
title
into individual words, which allows us to process each word separately. - Iterate over each word in the list of words.
- For each word, check its length:
- If it is less than 3 characters, convert the whole word to lowercase.
- Otherwise, use the
capitalize
method, which converts the first letter to uppercase and the rest of the letters to lowercase.
- After processing all words, join them back into a single string with a space separator.
- Return the resultant capitalized title string.
By following this method, we can apply the required capitalization logic to each word individually and construct the desired output in an efficient, Pythonic way.
Solution Approach
The implementation of the given solution involves the use of the Python list comprehension, a concise and readable way to generate a new list by applying an expression to each item in an iterable. The steps of the algorithm use fundamental Python data structures such as lists and strings, and they take advantage of string manipulation methods provided by Python's standard library.
Here's a walkthrough of the code and the patterns used:
-
title.split()
: This piece of code splits the input stringtitle
into a list of words. The.split()
method divides the string at each instance of the space character, which is the default delimiter. -
List comprehension:
[w.lower() if len(w) < 3 else w.capitalize() for w in title.split()]
: This is the core of the solution. It loops through each wordw
in the list of words obtained fromtitle.split()
. It applies the following logic to each word:w.lower()
is used whenlen(w) < 3
, meaning if the word length is less than 3 characters, this part of the ternary expression converts the entire word to lowercase.w.capitalize()
is used otherwise, which capitalizes the first letter of the word and makes all other letters lowercase.
-
" ".join(words)
: After the list comprehension generates the list of words adhering to the capitalization rules, this code joins the list back into a single string, separating each word with a space.
By combining the .split()
, .lower()
, .capitalize()
, and .join()
methods, the implementation elegantly navigates through the requirements without the need for complex algorithms or additional data structures. The solution is straightforward yet powerful, showing how well-chosen methods can make the code concise and effective.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's take a simple example to illustrate the solution approach. Suppose the input title
is "an example of a leetCode problem".
Following the steps of the solution:
-
We first use
title.split()
to split the input string into individual words. After this, our list of words will look like this: ["an", "example", "of", "a", "leetCode", "problem"]. -
Now the list comprehension comes into play. We process each word in the above list according to the length-based rules:
- "an" has 2 characters, so it is converted to lowercase: "an".
- "example" has 7 characters, so we capitalize the first letter: "Example".
- "of" has 2 characters, so it is converted to lowercase: "of".
- "a" has 1 character, so it is converted to lowercase: "a".
- "leetCode" has 8 characters, but with capitalization rule, it becomes: "Leetcode".
- "problem" has 7 characters, so we capitalize the first letter: "Problem".
-
Finally, we join the processed words back into one string with
" ".join(words)
, resulting in the final output: "an Example of a Leetcode Problem".
The list comprehension would look like this:
[w.lower() if len(w) < 3 else w.capitalize() for w in title.split()]
, and it simplifies the code by replacing a more elaborate for-loop with conditions into one compact line.
By the end of the process, we have successfully transformed the input string into a new string that follows the given capitalization rules.
Solution Implementation
1class Solution:
2 def capitalizeTitle(self, title: str) -> str:
3 # Split the title into words
4 words = title.split()
5
6 # Capitalize each word based on its length
7 # Words with less than 3 characters are kept lowercase
8 # Words with 3 or more characters are capitalized (first letter uppercase, remaining lowercase)
9 capitalized_words = [word.lower() if len(word) < 3 else word.capitalize() for word in words]
10
11 # Join the capitalized words back into a string with spaces
12 # and return the modified title
13 return " ".join(capitalized_words)
14
1class Solution {
2 public String capitalizeTitle(String title) {
3 // Create a list to store the processed words
4 List<String> capitalizedWords = new ArrayList<>();
5
6 // Split the title into individual words
7 String[] words = title.split(" ");
8
9 // Iterate through each word in the title
10 for (String word : words) {
11 // Check if the word length is less than 3
12 if (word.length() < 3) {
13 // Convert the entire word to lowercase and add to the list
14 capitalizedWords.add(word.toLowerCase());
15 } else {
16 // Capitalize only the first letter and convert the rest to lowercase,
17 // then add to the list
18 String capitalizedWord = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
19 capitalizedWords.add(capitalizedWord);
20 }
21 }
22
23 // Join the list elements into a string separated by spaces
24 return String.join(" ", capitalizedWords);
25 }
26}
27
1#include <sstream> // Include necessary header for string stream
2
3class Solution {
4public:
5 // Function to capitalize the title according to the specific rules
6 string capitalizeTitle(string title) {
7 // Convert the whole input string to lowercase
8 transform(title.begin(), title.end(), title.begin(), ::tolower);
9
10 istringstream title_stream(title); // Use string stream to read words
11 string result; // This will hold the final result
12 string word; // This will hold each word after being extracted from the stream
13
14 // Process each word in the input string
15 while (title_stream >> word) {
16 // Capitalize the first letter of words longer than 2 characters
17 if (word.size() > 2) word[0] = toupper(word[0]);
18
19 // Append the processed word to the result string
20 result += word + " ";
21 }
22
23 // Remove the trailing space added after processing the last word
24 if (!result.empty()) result.pop_back();
25
26 // Return the result string with appropriate capitalization
27 return result;
28 }
29};
30
1// Function to capitalize each word in a title string according to specific rules.
2// Words with a length less than 3 are kept in lowercase,
3// and words with a length of 3 or more have their first letter capitalized,
4// with the rest of the letters in lowercase.
5function capitalizeTitle(title: string): string {
6 // Initialize an array to hold the processed words.
7 const capitalizedWords: string[] = [];
8
9 // Split the title into words by spaces and iterate over each word.
10 for (const word of title.split(' ')) {
11 // Check the length of the word.
12 if (word.length < 3) {
13 // If the word is less than 3 characters long, add it to the array in lowercase.
14 capitalizedWords.push(word.toLowerCase());
15 } else {
16 // If the word is 3 characters or longer, capitalize the first letter
17 // and add the rest in lowercase to the array.
18 capitalizedWords.push(word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase());
19 }
20 }
21 // Join the processed words back into a single string with spaces in between and return it.
22 return capitalizedWords.join(' ');
23}
24
Time and Space Complexity
Time Complexity
The time complexity of the given code primarily depends on a few operations:
- The
split()
method, which runs inO(n)
wheren
is the length of the stringtitle
. - The list comprehension, which iterates over each word resulted from the
split()
operation. If there arem
words, it checks the length and either converts to lower case or capitalizes the word, which also takesO(n)
in total since each character in the title will be processed exactly once. - The
join()
method, which again works inO(n)
because it combines the words back into a single string, where the total number of characters is stilln
.
Hence, the overall time complexity is O(n)
because all operations are linear with respect to the length of the input string.
Space Complexity
For space complexity:
- A new list of words is created after the
split()
method, which requiresO(m)
space wherem
is the number of words in the title. - Each word is converted to a lower or capitalized word which creates temporary strings. However, since strings are immutable in Python, each transformation may create a new string, so the space required is also
O(n)
.
Therefore, the total space complexity of the algorithm is O(n)
, as it needs to store the transformed words equal to the total length of the input string.
Learn more about how to find time and space complexity quickly using problem constraints.
Which of the two traversal algorithms (BFS and DFS) can be used to find whether two nodes are connected?
Recommended Readings
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!