Title Case Converter - Problem

Given a sentence as a string, convert it to title case where the first letter of each word is capitalized and the rest are lowercase.

However, certain articles and prepositions should remain lowercase unless they are the first word of the sentence. These words include: 'a', 'an', 'the', 'and', 'but', 'or', 'for', 'nor', 'on', 'at', 'to', 'from', 'by', 'of', 'in'.

Rules:

  • The first word is always capitalized
  • Words not in the exception list are capitalized
  • Exception words remain lowercase unless they're the first word

Input & Output

Example 1 — Basic Case
$ Input: sentence = "the lord of the rings"
Output: "The Lord of the Rings"
💡 Note: First word 'the' becomes 'The', 'lord' becomes 'Lord', 'of' stays lowercase (exception), second 'the' stays lowercase (exception), 'rings' becomes 'Rings'
Example 2 — All Exceptions
$ Input: sentence = "a tale of two cities"
Output: "A Tale of Two Cities"
💡 Note: First word 'a' becomes 'A', 'tale' becomes 'Tale', 'of' stays lowercase (exception), 'two' becomes 'Two', 'cities' becomes 'Cities'
Example 3 — No Exceptions
$ Input: sentence = "harry potter"
Output: "Harry Potter"
💡 Note: No exception words present, so both 'harry' and 'potter' get capitalized to 'Harry Potter'

Constraints

  • 1 ≤ sentence.length ≤ 1000
  • sentence consists of lowercase/uppercase English letters and spaces
  • There is at least one word in the sentence

Visualization

Tap to expand
INPUTALGORITHMRESULTOriginal Sentence:"the lord of the rings"Words to process:thelordoftherings1Create exception set{a, an, the, and, but...}2Split into words3Check each word:- First word? Capitalize- In exception set? Lowercase- Otherwise? Capitalize4Join with spacesTitle Case Output:"The Lord of the Rings"Capitalization applied:TheLordoftheRingsGreen = CapitalizedRed = Exception (lowercase)Key Insight:Using a hash set for exception words enables O(1) lookup time instead of checkingagainst each exception individually, making the algorithm much more efficient.TutorialsPoint - Title Case Converter | Hash Set Optimization
Asked in
Google 25 Microsoft 18 Apple 15 Amazon 12
12.4K Views
Medium Frequency
~15 min Avg. Time
486 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen