LeetCode 2129 - Capitalize the Title

The problem asks us to transform the capitalization of every word in a given title string according to a specific rule based on word length. We are given a string called title, which contains one or more words separated by single spaces.

LeetCode Problem 2129

Difficulty: 🟢 Easy
Topics: String

Solution

Problem Understanding

The problem asks us to transform the capitalization of every word in a given title string according to a specific rule based on word length.

We are given a string called title, which contains one or more words separated by single spaces. Each word contains only English alphabet characters, and there are no leading or trailing spaces. Our task is to process every word independently and apply one of two capitalization rules:

  • If the word length is 1 or 2, the entire word must become lowercase.
  • If the word length is 3 or greater, the first character must become uppercase and all remaining characters must become lowercase.

The final result should be a newly formatted string with all transformed words joined together using spaces.

For example, the word "tHe" has length 3, so it becomes "The". The word "OF" has length 2, so it becomes "of".

The constraints are very small:

  • 1 <= title.length <= 100

This tells us that performance is not a major concern. Even less efficient solutions would still run quickly because the input size is tiny. However, the problem is primarily testing careful string manipulation and correct handling of capitalization rules.

There are several important edge cases to think about:

  • Single-character words such as "I" must become lowercase.
  • Two-character words such as "OF" must also become fully lowercase.
  • Words may already be correctly formatted, so we should not accidentally over-modify them.
  • Words may contain arbitrary uppercase and lowercase combinations, such as "cApiTalIZe".
  • Since the problem guarantees words are separated by single spaces and there are no leading or trailing spaces, we do not need to handle malformed spacing.

Approaches

Brute Force Approach

A straightforward brute-force solution is to manually process every character of every word.

We could split the title into words, then for each word:

  1. Check the length.
  2. If the length is 1 or 2, iterate through all characters and convert them to lowercase manually.
  3. Otherwise, uppercase the first character and lowercase all remaining characters manually.
  4. Concatenate all processed words back together.

This approach is correct because it explicitly applies the required capitalization rule to every character. However, it is unnecessarily verbose and error-prone because most programming languages already provide built-in string capitalization utilities.

Even though this approach is not actually too slow for the given constraints, it is more complicated than necessary and increases implementation complexity.

Optimal Approach

The key observation is that each word can be processed independently using built-in string methods.

We can:

  1. Split the string into words.
  2. For each word:
  • Convert the entire word to lowercase if its length is less than or equal to 2.
  • Otherwise, capitalize the first letter and lowercase the rest.
  1. Join the processed words back into a single string.

This works well because capitalization rules depend only on the current word, not on neighboring words. The built-in methods such as .lower() and .capitalize() in Python simplify the implementation significantly.

Approach Time Complexity Space Complexity Notes
Brute Force O(n) O(n) Manually processes every character
Optimal O(n) O(n) Uses built-in string operations for cleaner logic

Algorithm Walkthrough

  1. Split the input string into individual words using spaces.

This allows us to process each word independently. Since the problem guarantees exactly one space between words, the split operation is straightforward and reliable. 2. Create a result list to store transformed words.

Using a list is efficient because repeatedly concatenating strings can be slower in many languages. 3. Iterate through every word.

For each word, determine its length because the capitalization rule depends entirely on word size. 4. If the word length is 1 or 2, convert the entire word to lowercase.

Small words should not contain any uppercase characters according to the problem rules. 5. Otherwise, capitalize the word properly.

Convert the first letter to uppercase and the remaining letters to lowercase. In Python, .capitalize() conveniently performs exactly this transformation. 6. Append the transformed word to the result list.

This preserves the original word order. 7. Join all processed words with spaces.

The final output must maintain the original spacing structure.

Why it works

The algorithm works because every word is transformed independently according to the exact rule specified in the problem statement. Every possible word falls into exactly one of two categories:

  • Length 1 or 2
  • Length 3 or greater

The algorithm applies the correct transformation for each category, ensuring the final title satisfies all capitalization requirements.

Python Solution

class Solution:
    def capitalizeTitle(self, title: str) -> str:
        words = title.split()
        result = []

        for word in words:
            if len(word) <= 2:
                result.append(word.lower())
            else:
                result.append(word.capitalize())

        return " ".join(result)

The implementation begins by splitting the input string into individual words. This gives us a list where each element can be processed independently.

Next, we iterate through every word and check its length. If the word contains one or two characters, we convert the entire word to lowercase using .lower().

For longer words, we use .capitalize(), which automatically converts the first character to uppercase and the remaining characters to lowercase. This matches the required formatting exactly.

Finally, we join all transformed words back together using spaces and return the resulting string.

Go Solution

package main

import (
	"strings"
	"unicode"
)

func capitalizeTitle(title string) string {
	words := strings.Split(title, " ")

	for i, word := range words {
		word = strings.ToLower(word)

		if len(word) > 2 {
			runes := []rune(word)
			runes[0] = unicode.ToUpper(runes[0])
			word = string(runes)
		}

		words[i] = word
	}

	return strings.Join(words, " ")
}

The Go solution follows the same logic as the Python implementation. One difference is that Go does not provide a direct equivalent to Python's .capitalize() method, so we manually uppercase the first character after converting the entire word to lowercase.

We use []rune when modifying the first character because Go strings are immutable. Converting to runes also makes the implementation safer for Unicode handling, even though this problem only contains English letters.

Worked Examples

Example 1

Input:

title = "capiTalIze tHe titLe"

After splitting:

Index Word
0 "capiTalIze"
1 "tHe"
2 "titLe"

Processing steps:

Word Length Transformation Result
"capiTalIze" 10 Capitalize first letter "Capitalize"
"tHe" 3 Capitalize first letter "The"
"titLe" 5 Capitalize first letter "Title"

Final output:

"Capitalize The Title"

Example 2

Input:

title = "First leTTeR of EACH Word"

Processing:

Word Length Transformation Result
"First" 5 Capitalize "First"
"leTTeR" 6 Capitalize "Letter"
"of" 2 Lowercase all "of"
"EACH" 4 Capitalize "Each"
"Word" 4 Capitalize "Word"

Final output:

"First Letter of Each Word"

Example 3

Input:

title = "i lOve leetcode"

Processing:

Word Length Transformation Result
"i" 1 Lowercase all "i"
"lOve" 4 Capitalize "Love"
"leetcode" 8 Capitalize "Leetcode"

Final output:

"i Love Leetcode"

Complexity Analysis

Measure Complexity Explanation
Time O(n) Every character is processed at most a constant number of times
Space O(n) Extra space is used for split words and the final result

The algorithm processes each word independently and touches every character a constant number of times during lowercase and capitalization operations. Since the total number of characters is n, the overall runtime is linear.

The space complexity is also linear because splitting the string creates additional storage proportional to the input size.

Test Cases

solution = Solution()

# Provided examples
assert solution.capitalizeTitle("capiTalIze tHe titLe") == "Capitalize The Title"  # mixed capitalization
assert solution.capitalizeTitle("First leTTeR of EACH Word") == "First Letter of Each Word"  # short word handling
assert solution.capitalizeTitle("i lOve leetcode") == "i Love Leetcode"  # single-letter word

# Single word cases
assert solution.capitalizeTitle("HELLO") == "Hello"  # uppercase long word
assert solution.capitalizeTitle("hi") == "hi"  # two-letter word stays lowercase
assert solution.capitalizeTitle("A") == "a"  # single-letter uppercase

# Mixed casing
assert solution.capitalizeTitle("mIXed CaSe WORds") == "Mixed Case Words"  # arbitrary casing

# Boundary length words
assert solution.capitalizeTitle("an APPLE a DAY") == "an Apple a Day"  # 1 and 2 length handling

# Already formatted
assert solution.capitalizeTitle("This Is Fine") == "This is Fine"  # two-letter word corrected

# All short words
assert solution.capitalizeTitle("to be or no") == "to be or no"  # all remain lowercase
Test Why
"capiTalIze tHe titLe" Verifies standard capitalization
"First leTTeR of EACH Word" Verifies two-letter lowercase rule
"i lOve leetcode" Verifies single-letter handling
"HELLO" Verifies full uppercase normalization
"hi" Verifies lowercase preservation
"A" Verifies single uppercase character conversion
"mIXed CaSe WORds" Verifies arbitrary mixed-case inputs
"an APPLE a DAY" Verifies mixed short and long words
"This Is Fine" Verifies correction of two-letter capitalized words
"to be or no" Verifies all-short-word input

Edge Cases

One important edge case is single-character words such as "I" or "A". These words must become fully lowercase, even if they originally contain uppercase letters. A naive implementation that capitalizes every word would incorrectly produce "I" instead of "i". Our implementation explicitly checks word length and correctly lowercases all one-character words.

Another important edge case is two-character words such as "OF" or "Is". These words also require complete lowercase conversion. This is easy to overlook because many title-formatting conventions capitalize words like "Is" or "Of". However, this problem has its own custom capitalization rules, and our solution follows them exactly.

A third edge case involves words with unusual capitalization patterns, such as "cApItALiZe". Simply uppercasing the first letter is not enough because the remaining letters must also become lowercase. Our implementation solves this by either using .capitalize() in Python or explicitly lowercasing the whole word before uppercasing the first character in Go.