Capitalize the Title

Easy
#1939Time: 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.
Data structures

Prompt

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.
  • 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 <= 100
  • title consists 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 title string by spaces to get an array of words.
  • Initialize a StringBuilder to construct the result.
  • Loop through each word in the words array.
  • If word.length() <= 2, append the lowercase version of the word to the StringBuilder.
  • Otherwise, append the first character of the word in uppercase, followed by the rest of the word in 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.

Solutions

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);    }}

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.