212 lines
9.3 KiB
YAML
212 lines
9.3 KiB
YAML
title: Capitalize the Title
|
|
slug: capitalize-the-title
|
|
difficulty: easy
|
|
leetcode_id: 2129
|
|
leetcode_url: https://leetcode.com/problems/capitalize-the-title/
|
|
categories:
|
|
- strings
|
|
patterns:
|
|
- two-pointers
|
|
|
|
function_signature: "def capitalize_title(title: str) -> str:"
|
|
|
|
test_cases:
|
|
visible:
|
|
- input: { title: "capiTalIze tHe titLe" }
|
|
expected: "Capitalize The Title"
|
|
- input: { title: "First leTTeR of EACH Word" }
|
|
expected: "First Letter of Each Word"
|
|
- input: { title: "i lOve leetcode" }
|
|
expected: "i Love Leetcode"
|
|
hidden:
|
|
- input: { title: "TO BE OR NOT TO BE" }
|
|
expected: "to be or Not to be"
|
|
- input: { title: "a" }
|
|
expected: "a"
|
|
- input: { title: "AB" }
|
|
expected: "ab"
|
|
- input: { title: "ABC" }
|
|
expected: "Abc"
|
|
- input: { title: "the QUICK brown FOX" }
|
|
expected: "The Quick Brown Fox"
|
|
|
|
description: |
|
|
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`.
|
|
|
|
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**.
|
|
|
|
examples:
|
|
- 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."
|
|
- 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.'
|
|
- 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.'
|
|
|
|
explanation:
|
|
intuition: |
|
|
Think of this problem like editing a book title according to specific style rules. When you see a title like "tHE quICk FOX", you need to normalise each word based on its length.
|
|
|
|
The core insight is that each word operates **independently** — the capitalisation rule for one word doesn't depend on any other word. This means we can process the string word by word.
|
|
|
|
Imagine you're a copy editor with a simple checklist:
|
|
- Is this word tiny (1-2 letters)? Make it all lowercase.
|
|
- Is this word longer? Capitalise only the first letter, lowercase the rest.
|
|
|
|
Since words are separated by single spaces with no leading/trailing spaces, we can simply split the string, transform each word according to our rules, and join them back together.
|
|
|
|
approach: |
|
|
We solve this using a **Word-by-Word Transformation** approach:
|
|
|
|
**Step 1: Split the string into words**
|
|
|
|
- Use the `split()` method to break the title into individual words
|
|
- Each word will be processed independently
|
|
|
|
|
|
|
|
**Step 2: Transform each word based on its length**
|
|
|
|
- For each word, check its length:
|
|
- If `len(word) <= 2`: convert the entire word to lowercase using `lower()`
|
|
- If `len(word) >= 3`: capitalise using `capitalize()` (first letter uppercase, rest lowercase)
|
|
|
|
|
|
|
|
**Step 3: Join the transformed words**
|
|
|
|
- Use `' '.join()` to combine all transformed words back into a single string
|
|
- The single space separator preserves the original spacing
|
|
|
|
|
|
|
|
This approach leverages Python's built-in string methods for clean, readable code.
|
|
|
|
common_pitfalls:
|
|
- title: Forgetting to Lowercase the Rest
|
|
description: |
|
|
A common mistake is only uppercasing the first letter without lowercasing the remaining letters.
|
|
|
|
For example, with `"HELLO"`, if you only uppercase the first letter, you'd get `"HELLO"` instead of `"Hello"`.
|
|
|
|
Python's `capitalize()` method handles this correctly — it uppercases the first character and lowercases all others. Using `title()` would be incorrect as it capitalises every word regardless of length.
|
|
wrong_approach: "Only uppercase first letter: word[0].upper() + word[1:]"
|
|
correct_approach: "Use capitalize() which lowercases the rest: word.capitalize()"
|
|
|
|
- title: Using title() Method
|
|
description: |
|
|
Python's built-in `title()` method might seem perfect, but it capitalises **every** word regardless of length.
|
|
|
|
For `"i lOve leetcode"`, using `title()` gives `"I Love Leetcode"` — but "i" should stay lowercase since it has only 1 letter.
|
|
|
|
We need custom logic that checks word length before deciding how to capitalise.
|
|
wrong_approach: 'title.title()'
|
|
correct_approach: "Check length first, then apply lowercase or capitalize"
|
|
|
|
- title: Off-by-One in Length Check
|
|
description: |
|
|
The rule specifies words with length `1` or `2` should be lowercase. Make sure your condition is `<= 2` not `< 2`.
|
|
|
|
With `len(word) < 2`, you'd only lowercase single-letter words, incorrectly capitalising two-letter words like "of" or "to".
|
|
wrong_approach: "if len(word) < 2: word.lower()"
|
|
correct_approach: "if len(word) <= 2: word.lower()"
|
|
|
|
key_takeaways:
|
|
- "**String splitting pattern**: When processing words independently, `split()` and `join()` provide a clean transformation pipeline"
|
|
- "**Built-in methods**: Python's `capitalize()` handles both uppercasing first and lowercasing rest — know your standard library"
|
|
- "**Read requirements carefully**: The length threshold (`<= 2`) is crucial; off-by-one errors are common"
|
|
- "**Simple problems, clean code**: Resist over-engineering; list comprehensions keep this solution readable and Pythonic"
|
|
|
|
time_complexity: "O(n). We process each character in the string exactly once during split, transformation, and join operations."
|
|
space_complexity: "O(n). We create a new list of words and a new result string, both proportional to the input size."
|
|
|
|
solutions:
|
|
- approach_name: Word-by-Word Transformation
|
|
is_optimal: true
|
|
code: |
|
|
def capitalize_title(title: str) -> str:
|
|
# Split the title into individual words
|
|
words = title.split()
|
|
|
|
# Transform each word based on its length
|
|
result = []
|
|
for word in words:
|
|
if len(word) <= 2:
|
|
# Short words (1-2 letters) are all lowercase
|
|
result.append(word.lower())
|
|
else:
|
|
# Longer words: first letter uppercase, rest lowercase
|
|
result.append(word.capitalize())
|
|
|
|
# Join words back with single spaces
|
|
return ' '.join(result)
|
|
explanation: |
|
|
**Time Complexity:** O(n) — We iterate through all characters once.
|
|
|
|
**Space Complexity:** O(n) — We store the transformed words and result string.
|
|
|
|
This approach splits the string, processes each word according to the length rules, and joins them back. Python's built-in `capitalize()` handles the case conversion cleanly.
|
|
|
|
- approach_name: List Comprehension
|
|
is_optimal: true
|
|
code: |
|
|
def capitalize_title(title: str) -> str:
|
|
# One-liner using conditional expression in list comprehension
|
|
return ' '.join(
|
|
word.lower() if len(word) <= 2 else word.capitalize()
|
|
for word in title.split()
|
|
)
|
|
explanation: |
|
|
**Time Complexity:** O(n) — Same as the explicit loop version.
|
|
|
|
**Space Complexity:** O(n) — Generator expression still builds the result list.
|
|
|
|
This is a more Pythonic version using a generator expression with a conditional. It's concise while remaining readable, applying the same logic as the explicit loop.
|
|
|
|
- approach_name: In-Place Character Processing
|
|
is_optimal: false
|
|
code: |
|
|
def capitalize_title(title: str) -> str:
|
|
# Convert to list for mutability
|
|
chars = list(title.lower())
|
|
n = len(chars)
|
|
|
|
i = 0
|
|
while i < n:
|
|
# Find the start of the next word
|
|
word_start = i
|
|
|
|
# Find the end of the current word
|
|
while i < n and chars[i] != ' ':
|
|
i += 1
|
|
word_end = i
|
|
|
|
# Calculate word length
|
|
word_length = word_end - word_start
|
|
|
|
# If word has 3+ characters, capitalize first letter
|
|
if word_length >= 3:
|
|
chars[word_start] = chars[word_start].upper()
|
|
|
|
# Move past the space
|
|
i += 1
|
|
|
|
return ''.join(chars)
|
|
explanation: |
|
|
**Time Complexity:** O(n) — Single pass through the string.
|
|
|
|
**Space Complexity:** O(n) — We convert string to list for mutability.
|
|
|
|
This approach processes characters directly, first lowercasing everything, then capitalising the first letter of words with 3+ characters. While it avoids creating intermediate word arrays, it's more complex and doesn't improve actual performance in Python due to string immutability.
|