Capitalize the Title
EasyPrompt
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.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach is straightforward and relies on high-level string functions. It involves splitting the title into words, processing each word individually based on the capitalization rules, and then joining them back into a single string.
Algorithm
- Split the
titlestring by spaces to get an array ofwords. - Initialize a
StringBuilderto construct the result. - Loop through each
wordin thewordsarray. - If
word.length() <= 2, append the lowercase version of thewordto theStringBuilder. - Otherwise, append the first character of the
wordin uppercase, followed by the rest of thewordin lowercase. - Append a space after each word, except the last one.
- Return the final string from the
StringBuilder.
Walkthrough
The algorithm first splits the input title string into an array of words using the space character as a delimiter. It then iterates through this array. For each word, it checks its length. If the length is 2 or less, the entire word is converted to lowercase. If the length is 3 or more, the first letter is converted to uppercase and the remaining letters are converted to lowercase. A StringBuilder is used to efficiently build the final string by appending each processed word followed by a space (except for the last word).
class Solution { public String capitalizeTitle(String title) { String[] words = title.split(" "); StringBuilder result = new StringBuilder(); for (int i = 0; i < words.length; i++) { String word = words[i]; if (word.length() <= 2) { result.append(word.toLowerCase()); } else { result.append(Character.toUpperCase(word.charAt(0))); result.append(word.substring(1).toLowerCase()); } if (i < words.length - 1) { result.append(" "); } } return result.toString(); }}Complexity
Time
O(N), where N is the length of the `title`. The `split` operation, the loop through words (which involves operations like `toLowerCase` and `substring` that are proportional to word length), and building the final string all contribute to a linear time complexity.
Space
O(N), where N is the length of the `title`. Space is required for the array of words created by `split()` and for the `StringBuilder` used to construct the output.
Trade-offs
Pros
Simple and easy to understand.
Leverages standard library functions, leading to concise code.
Cons
Less memory-efficient due to the creation of an intermediate array of strings.
Involves creating multiple temporary string objects during processing (e.g., from
toLowerCase,substring), which can increase garbage collection overhead.
This is a more optimized approach that avoids creating intermediate string arrays and performs the capitalization in a single pass over the string's characters. It modifies a character array representation of the string directly, making it more efficient in terms of both time and memory.
Algorithm
- Convert the input
titlestring to a character arraychars. - Initialize an index
i = 0to iterate through the string. - Use a
forloop that continues as long asiis less than the string length. - Inside the loop, mark the start of a word with
wordStart = i. - Use an inner
whileloop to find the end of the word. In this loop, convert every character to lowercase and advancei. - After the inner loop, the word from
wordStarttoi-1has been processed (all lowercase). Check its length (i - wordStart). - If the length is greater than 2, convert the character at
chars[wordStart]to uppercase. - The outer loop will naturally advance
ipast the space to the start of the next word. - After the loop, create and return a new string from the modified
charsarray.
Walkthrough
The algorithm begins by converting the input title into a character array for efficient modification. It then iterates through this array in a single pass. It uses a pointer i that moves from start to end. When i is at the beginning of a word, it marks that position. Then, an inner loop moves i to the end of that word, converting all its characters to lowercase along the way. Once the word is fully scanned, its length is checked. If the length is greater than 2, the character at the marked start position is capitalized. This process repeats for all words. This single-pass method minimizes object allocations and data copying.
class Solution { public String capitalizeTitle(String title) { char[] chars = title.toCharArray(); int n = chars.length; for (int i = 0; i < n; ++i) { // Mark the start of a word int wordStart = i; // Iterate to the end of the word while (i < n && chars[i] != ' ') { // Convert current character to lowercase chars[i] = Character.toLowerCase(chars[i]); i++; } // After the loop, 'i' is at a space or end of string. // The word is from 'wordStart' to 'i - 1'. // Check word length and capitalize if needed. if (i - wordStart > 2) { chars[wordStart] = Character.toUpperCase(chars[wordStart]); } } return new String(chars); }}Complexity
Time
O(N), where N is the length of the `title`. Although there is a nested loop structure, the outer loop's index `i` is advanced by the inner loop. This ensures that each character of the string is processed only once, resulting in a linear time complexity.
Space
O(N) to store the character array `chars`. Since strings are immutable in Java, a new character array or `StringBuilder` is necessary to perform modifications.
Trade-offs
Pros
Most efficient in terms of time and memory.
Avoids creating intermediate string arrays and objects.
Processes the string in a single pass.
Cons
The logic is slightly more complex, involving manual index management.
Code can be less readable than the high-level
split/joinapproach for those unfamiliar with this pattern.
Solutions
Solution
public class Solution { public string CapitalizeTitle(string title) { List < string > ans = new List < string > (); foreach(string s in title.Split(' ')) { if (s.Length < 3) { ans.Add(s.ToLower()); } else { ans.Add(char.ToUpper(s[0]) + s.Substring(1).ToLower()); } } return string.Join(" ", ans); }}class Solution {public String capitalizeTitle(String title) { List<String> ans = new ArrayList<>(); for (String s : title.split(" ")) { if (s.length() < 3) { ans.add(s.toLowerCase()); } else { ans.add(s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase()); } } return String.join(" ", ans); }}class Solution {public: string capitalizeTitle(string title) { transform(title.begin(), title.end(), title.begin(), ::tolower); istringstream ss(title); string ans; while (ss >> title) { if (title.size() > 2) title[0] = toupper(title[0]); ans += title; ans += " "; } ans.pop_back(); return ans; }};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)Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.