If you’re tackling string manipulation problems on LeetCode, Problem 2129: Capitalize the Title is a great one to master. It challenges your understanding of word boundaries, character casing, and clean iteration—all crucial in interviews and real-world applications.
🔍 Problem Summary
You’re given a string title
containing words separated by spaces. Transform it based on the following rules:
- Words with ≤ 2 letters → Convert all characters to lowercase
- Words with ≥ 3 letters → Capitalize the first character, lowercase the rest
Example:
Input: "capiTalIze tHe titLe"
Output: "Capitalize The Title"
🧠 Approach & Solutions in Multiple Languages
✅ C++: Two-Pointer + In-Place Modification
class Solution {
public:
string capitalizeTitle(string title) {
ranges::transform(title, title.begin(), ::tolower); // Convert entire string to lowercase
int i = 0, j = 0;
while (j < title.length()) {
while (j < title.length() && title[j] != ' ') j++;
if (j - i > 2) title[i] = toupper(title[i]);
i = j + 1;
j++;
}
return title;
}
};
- Time: O(n)
- Space: O(1)
✅ Java: Efficient String Manipulation with StringBuilder
class Solution {
public String capitalizeTitle(String title) {
StringBuilder sb = new StringBuilder(title.toLowerCase());
int i = 0, j = 0;
while (j < sb.length()) {
while (j < sb.length() && sb.charAt(j) != ' ') j++;
if (j - i > 2) sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
i = j + 1;
j++;
}
return sb.toString();
}
}
- Time: O(n)
- Space: O(n)
✅ Python: Clean and Pythonic
class Solution:
def capitalizeTitle(self, title: str) -> str:
return ' '.join(s.lower() if len(s) < 3 else s.capitalize() for s in title.split())
- Time: O(n)
- Space: O(n)
✅ C#: Optimized with List<char>
(Approach 3)
public string CapitalizeTitle(string title) {
List<char> result = new List<char>(title.ToLower());
int start = 0;
for (int i = 0; i <= result.Count; i++) {
if (i == result.Count || result[i] == ' ') {
int length = i - start;
if (length > 2) result[start] = char.ToUpper(result[start]);
start = i + 1;
}
}
return new string(result.ToArray());
}
- Time: O(n)
- Space: O(n)
💡 Optimization Tips
- C++ / C#: Prefer in-place edits (e.g., using
List<char>
or direct string mutation) for optimal memory use. - Java / C#:
StringBuilder
reduces the overhead from string concatenation. - Python:
split()
andjoin()
make concise, readable solutions.
📊 Complexity Comparison
Language | Time Complexity | Space Complexity | Key Strategy |
---|---|---|---|
C++ | O(n) | O(1) | In-place two-pointer |
Java | O(n) | O(n) | StringBuilder traversal |
Python | O(n) | O(n) | Functional string methods |
C# | O(n) | O(n) | List-based in-place logic |
🔗 What to Practice Next
- Leverage this logic in similar problems like:
- Capitalizing headings
- Title case conversion in a sentence
- Word-based transformation using character conditions
Need more practice? Check out the LeetCode official practice portal to sharpen your skills.