3711. First Letter Capitalization II
My accepted SQL solution to LeetCode problem 3711, First Letter Capitalization II, running in 364ms.
- Difficulty: Hard
- SQL
- Runtime 364ms
- Memory 0.0B
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
SQL
Accepted on LeetCode — runtime 364ms, memory 0.0B, accepted 2025-12-31.
# Write your MySQL query statement below
WITH RECURSIVE numbers AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 1000
),
words AS (
SELECT
content_id,
content_text AS original_text,
n AS word_pos,
SUBSTRING_INDEX(SUBSTRING_INDEX(content_text, ' ', n), ' ', -1) AS word
FROM user_content
CROSS JOIN numbers
WHERE n <= LENGTH(content_text) - LENGTH(REPLACE(content_text, ' ', '')) + 1
),
parts AS (
SELECT
content_id,
original_text,
word_pos,
word,
m AS part_pos,
SUBSTRING_INDEX(SUBSTRING_INDEX(word, '-', m), '-', -1) AS part
FROM words
CROSS JOIN (SELECT 1 AS m UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) mults
WHERE m <= LENGTH(word) - LENGTH(REPLACE(word, '-', '')) + 1
),
cap_parts AS (
SELECT
content_id,
original_text,
word_pos,
word,
part_pos,
CONCAT(UPPER(LEFT(part, 1)), LOWER(SUBSTRING(part, 2))) AS cap_part
FROM parts
),
cap_words AS (
SELECT
content_id,
original_text,
word_pos,
GROUP_CONCAT(cap_part ORDER BY part_pos SEPARATOR '-') AS cap_word
FROM cap_parts
GROUP BY content_id, original_text, word_pos, word
)
SELECT
content_id,
original_text,
GROUP_CONCAT(cap_word ORDER BY word_pos SEPARATOR ' ') AS converted_text
FROM cap_words
GROUP BY content_id, original_text
ORDER BY content_id;