#2129
Capitalize the Title
EasyStringString manipulationArray processing
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach processes each word in a single pass without unnecessary string manipulations. By using a list to collect results, we can efficiently build the final string.
⚙️
Algorithm
4 steps- 1Step 1: Split the input string into words.
- 2Step 2: Initialize an empty list to store the modified words.
- 3Step 3: For each word, apply the capitalization rules based on its length and add it to the list.
- 4Step 4: Join the list into a single string and return it.
solution.py11 lines
1# Full working Python code
2
3def capitalizeTitle(title):
4 words = title.split()
5 result = []
6 for word in words:
7 if len(word) <= 2:
8 result.append(word.lower())
9 else:
10 result.append(word[0].upper() + word[1:].lower())
11 return ' '.join(result)ℹ
Complexity note: The time complexity is O(n) because we process each character in the string exactly once. The space complexity is O(n) due to the storage of the words in a list before joining them.
- 1Understanding the rules for capitalization based on word length is crucial.
- 2Efficient string manipulation can significantly reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.