Skip to main content

First Letter Capitalization II - Solution & Explanation

HardDatabase7 min read
Practice this problem

Problem Statement

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)
  • 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.

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.

Code

Python

JavaScript

Complexity

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.

Try this approach in the editor →

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.

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.

Code

SQL

Complexity

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.

Try this approach in the editor →

Approach 3: Default Approach

Code

Pandas

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
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.
Space Complexity: O(n), required for storing the capitalized words.

SQL Query with User Defined Function

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.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
String Manipulation with Regular ExpressionsO(n)O(n)When processing text in application code using Python or JavaScript
SQL Query with User Defined FunctionO(n)O(1)When the transformation must happen directly in the database layer

Video Solution

LeetCode 3374: First Letter Capitalization II | Easy String Problem Explained Simply #leetcode #3374 • InsightVanta • 869 views views

Watch 2 more video solutions →

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.

Ready to solve this problem?

Practice First Letter Capitalization II with our built-in code editor and test cases.

Practice on FleetCode