First Letter Capitalization II solution and explanation
2 more videos on this problem
LeetCode 3374: First Letter Capitalization II | Easy String Problem Explained Simply #leetcode #3374InsightVanta · 25:06 · 869 views
First Letter Capitalization IIOwen Wu · 2:23 · 113 views
First Letter Capitalization II – LeetCode 3374 Explained (PostgreSQL Tutorial)Sumanshu Nankana · 47:31 · 100 views
The problem
Table: user_content
+-------------+---------+ | Column Name | Type | +-------------+---------+ | content_id | int | | content_text| varchar | +-------------+---------+ content_id is the unique key for this table. Each row contains a unique ID and the corresponding text content.
Write a solution to transform the text in the content_text column by applying the following rules:
- Convert the first letter of each word to uppercase and the remaining letters to lowercase
- Special handling for words containing special characters:
- For words connected with a hyphen
-, both parts should be capitalized (e.g., top-rated → Top-Rated)
- For words connected with a hyphen
- All other formatting and spacing should remain unchanged
Return the result table that includes both the original content_text and the modified text following the above rules.
The result format is in the following example.
Example:
Input:
user_content table:
+------------+---------------------------------+ | content_id | content_text | +------------+---------------------------------+ | 1 | hello world of SQL | | 2 | the QUICK-brown fox | | 3 | modern-day DATA science | | 4 | web-based FRONT-end development | +------------+---------------------------------+
Output:
+------------+---------------------------------+---------------------------------+ | content_id | original_text | converted_text | +------------+---------------------------------+---------------------------------+ | 1 | hello world of SQL | Hello World Of Sql | | 2 | the QUICK-brown fox | The Quick-Brown Fox | | 3 | modern-day DATA science | Modern-Day Data Science | | 4 | web-based FRONT-end development | Web-Based Front-End Development | +------------+---------------------------------+---------------------------------+
Explanation:
- For content_id = 1:
- Each word's first letter is capitalized: "Hello World Of Sql"
- For content_id = 2:
- Contains the hyphenated word "QUICK-brown" which becomes "Quick-Brown"
- Other words follow normal capitalization rules
- For content_id = 3:
- Hyphenated word "modern-day" becomes "Modern-Day"
- "DATA" is converted to "Data"
- For content_id = 4:
- Contains two hyphenated words: "web-based" → "Web-Based"
- And "FRONT-end" → "Front-End"
Approach overview
Problem Overview: You are given text stored in a database column and need to convert it so that the first character of every word is capitalized while the remaining characters stay lowercase. The transformation must handle word boundaries correctly and return the normalized string for each row.
Approach 1: String Manipulation with Regular Expressions (O(n) time, O(n) space)
This approach processes each string using a regular expression that identifies word boundaries and capitalizes the first character of each match. In Python or JavaScript, you scan the string once while applying a regex like \b[a-z] or similar patterns to capture the first letter of each word. The replacement function converts the captured character to uppercase while preserving the rest of the string. Since the regex engine walks through the input once, the time complexity is O(n) per string and the space complexity is O(n) due to the new transformed string.
This method is concise and easy to maintain. It is especially useful in application-level processing where you already fetch rows from the database and perform transformations using languages like Python or JavaScript. If you are comfortable with string manipulation and regular expressions, this approach provides a clean and expressive implementation.
Approach 2: SQL Query with User Defined Function (O(n) time, O(1) auxiliary space)
The database-centric approach performs capitalization directly inside SQL using a user defined function (UDF). The function iterates through characters of the input string and capitalizes letters that follow a word boundary such as a space or punctuation. Some SQL engines also support regex-based replacements, allowing expressions like REGEXP_REPLACE to convert the first letter of each word. Each row is processed independently, scanning the string once, giving O(n) time complexity per row.
This solution keeps the logic close to the data and avoids round trips to the application layer. It is often preferred when working heavily with database queries or when the transformation must be applied during reporting or ETL pipelines.
Recommended for interviews: The regex-based string manipulation approach is usually the clearest explanation during interviews because it demonstrates knowledge of word boundary detection and efficient linear-time processing. Mentioning the SQL UDF solution shows awareness of database-side transformations, which is valuable for backend or data engineering roles.
Approach 1: String Manipulation with Regular Expressions
This approach involves splitting the text into words, identifying hyphenated words, and capitalizing parts separately. Regular expressions can guide this transformation effectively, ensuring that both normal and hyphenated words are correctly capitalized.
import re
def capitalize_text(text):
def capitalize_word(word):
# Handle hyphenated words
return '-'.join([w.capitalize() for w in word.split('-')])
# Use regex to split text by whitespace, preserving hyphenated words
return ' '.join([capitalize_word(word) for word in re.split(' ', text)])
# Example application
texts = [
'hello world of SQL',
'the QUICK-brown fox',
'modern-day DATA science',
'web-based FRONT-end development'
]
# Transform each text according to rules
converted_texts = [capitalize_text(text) for text in texts]
print(converted_texts)function capitalizeText(text) {
function capitalizeWord(word) {
return word.split('-').map(part => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join('-');
}
return text.split(' ').map(capitalizeWord).join(' ');
}
// Example application
const texts = [
'hello world of SQL',
'the QUICK-brown fox',
'modern-day DATA science',
'web-based FRONT-end development'
];
// Transform each text according to rules
const convertedTexts = texts.map(capitalizeText);
console.log(convertedTexts);This Python function utilizes regular expressions to split the input text, handle each word separately, and manage hyphenated words by splitting them at the hyphen character. Each part of a hyphenated word is capitalized before being recombined. The capitalize() method is used to capitalize the first letter of each word.
Time Complexity: O(n), where n is the number of characters in the text. The function iterates over each word and split operations are efficient.
Space Complexity: O(n), required for storing the capitalized words.
Approach 2: SQL Query with User Defined Function
Utilizing SQL and defining a custom function to handle text transformation directly in the database. SQL natively supports string manipulations with functions like UPPER() and LOWER(), which can be leveraged to perform this task.
-- Assuming we have a SQL database that supports custom functions
CREATE FUNCTION capitalizeText(input_text VARCHAR(255)) RETURNS VARCHAR(255) DETERMINISTIC
BEGIN
DECLARE output_text VARCHAR(255);
DECLARE word VARCHAR(255);
DECLARE char_pos INT DEFAULT 1;
DECLARE hyphen_pos INT;
DECLARE len INT DEFAULT LENGTH(input_text);
SET output_text = '';
WHILE char_pos <= len DO
SET word = '';
-- Find the next space
WHILE char_pos <= len AND SUBSTRING(input_text, char_pos, 1) != ' ' DO
SET word = CONCAT(word, SUBSTRING(input_text, char_pos, 1));
SET char_pos = char_pos + 1;
END WHILE;
-- Handle hyphenated words
IF LOCATE('-', word) THEN
SET hyphen_pos = LOCATE('-', word);
SET word = CONCAT(UPPER(SUBSTRING(word, 1, 1)),
LOWER(SUBSTRING(word, 2, hyphen_pos - 1)),
'-',
UPPER(SUBSTRING(word, hyphen_pos + 1, 1)),
LOWER(SUBSTRING(word, hyphen_pos + 2)));
ELSE
SET word = CONCAT(UPPER(SUBSTRING(word, 1, 1)), LOWER(SUBSTRING(word, 2)));
END IF;
SET output_text = CONCAT(output_text, ' ', word);
SET char_pos = char_pos + 1;
END WHILE;
RETURN TRIM(output_text);
END;
-- Use this function in a SELECT query
SELECT content_id, content_text, capitalizeText(content_text) AS converted_text FROM user_content;This SQL function processes each row in the table, identifies individual words and handles hyphenated ones in text strings, transforming them using string functions to capitalize the appropriate letters. The function supports iterative examination of text and concatenation for output.
Time Complexity: O(n), where n is the length of the input text.
Space Complexity: O(1), as the function operates directly on inputs without additional data structures.
Approach 3: Default Approach
import pandas as pd
def capitalize_content(user_content: pd.DataFrame) -> pd.DataFrame:
def convert_text(text: str) -> str:
return " ".join(
(
"-".join([part.capitalize() for part in word.split("-")])
if "-" in word
else word.capitalize()
)
for word in text.split(" ")
)
user_content["converted_text"] = user_content["content_text"].apply(convert_text)
return user_content.rename(columns={"content_text": "original_text"})[
["content_id", "original_text", "converted_text"]
]Complexity comparison
| Approach | Complexity |
|---|---|
| String Manipulation with Regular Expressions | Time Complexity: O(n), where n is the number of characters in the text. The function iterates over each word and split operations are efficient. |
| SQL Query with User Defined Function | Time Complexity: O(n), where n is the length of the input text. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| String Manipulation with Regular Expressions | O(n) | O(n) | When processing text in application code using Python or JavaScript |
| SQL Query with User Defined Function | O(n) | O(1) | When the transformation must happen directly in the database layer |
Frequently asked questions
Is First Letter Capitalization II easy or hard?
The problem is labeled Hard on some platforms because it combines database querying with string normalization logic. The core algorithm is linear-time string processing, but implementing it correctly in SQL or with regex patterns can require careful handling of word boundaries.
First Letter Capitalization II Python/Java solution
In Python, the problem is typically solved using the re.sub function with a pattern like \b[a-z] and a lambda that converts matches to uppercase. In JavaScript, String.replace with a regex and callback performs the same operation. SQL solutions rely on REGEXP_REPLACE or a user defined function that iterates through characters.
How to solve First Letter Capitalization II in O(n)?
Process the string once and capitalize characters that appear at word boundaries. In Python or JavaScript, a regex like \b[a-z] can match the first character of each word and replace it with its uppercase version. Since each character is visited once during matching and replacement, the algorithm runs in O(n) time.
What is the best approach for First Letter Capitalization II?
The most practical approach is using regular expressions to detect word boundaries and capitalize the first character of each word. Regex-based solutions run in O(n) time for each string and are easy to implement in Python or JavaScript. When the transformation must happen inside the database, a SQL user defined function or REGEXP_REPLACE query provides the same linear-time behavior.
Is First Letter Capitalization II asked at Google/Amazon/Meta?
String normalization and text formatting problems appear frequently in backend and data engineering interviews at companies like Amazon and Google. Variants involving capitalization, tokenization, or regex processing are common when evaluating string manipulation and database query skills.
What data structure is used in First Letter Capitalization II?
The problem mainly relies on string processing rather than complex data structures. Implementations use regular expression engines or sequential character iteration to detect word boundaries and modify characters accordingly.
What is the time complexity of First Letter Capitalization II?
The typical solution scans each character of the string once, giving O(n) time complexity where n is the length of the text. Regex engines internally perform a linear scan for simple word-boundary patterns. Space complexity is O(n) if a new transformed string is created.
