Problem solution · SQL

First Letter Capitalization

First Letter Capitalization: a SQL solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
47 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For First Letter Capitalization, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 47 lines of SQL from the credited upstream file 3368.sql.
  • The implementation keeps its working state in language-native values and containers.
  • No explicit loop blocks detected.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFirst Letter Capitalization · SQLSQL
Use this to learn the idea, then write your own version.
WITH RECURSIVE  Words AS (    -- Extract the first word and assign a token index.    SELECT      content_id,      SUBSTRING_INDEX(content_text, ' ', 1) AS word,      SUBSTRING(        content_text,        LENGTH(SUBSTRING_INDEX(content_text, ' ', 1)) + 2      ) AS remaining_text,      1 AS token_index    FROM user_content    UNION ALL    -- Recursively extract the next word and increment the token index.    SELECT      content_id,      SUBSTRING_INDEX(remaining_text, ' ', 1) AS word,      SUBSTRING(        remaining_text,        LENGTH(SUBSTRING_INDEX(remaining_text, ' ', 1)) + 2      ) AS remaining_text,      token_index + 1 AS token_index    FROM Words    WHERE remaining_text != ''  ),  Converted AS (    -- Combine the words back in original order with proper capitalization.    SELECT      content_id,      GROUP_CONCAT(        CONCAT(          UPPER(SUBSTRING(word, 1, 1)),          LOWER(SUBSTRING(word, 2))        )        ORDER BY token_index SEPARATOR ' '      ) AS converted_text    FROM Words    GROUP BY 1  )SELECT  UserContent.content_id,  UserContent.content_text AS original_text,  Converted.converted_textFROM user_content AS UserContentINNER JOIN Converted  USING (content_id); 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗