Problem Statement
Capitalize the first letter of each word in a string.
Example Inputs
- Input:
"hello world"
- Input:
"javascript is fun"
- Output:
"Javascript Is Fun"
- Input:
"openai gpt model"
- Output:
"Openai Gpt Model"
- Input:
"capitalize each word"
- Output:
"Capitalize Each Word"
JavaScript Method - Using Only String Methods
Approach
To capitalize the first letter of each word, we can split the string into an array of words, capitalize each word’s first letter, and then join the array back into a string.
Steps
- Use
.split(' ')
to split the string into an array of words.
- Loop through the array of words.
- For each word, capitalize the first letter using
.charAt(0).toUpperCase()
and add the rest of the word in lowercase with .slice(1)
.
- Join the array back into a string using
.join(' ')
.
- Return the resulting string.
Time & Space Complexity
- Time Complexity: O(n), where n is the total number of characters in the string, as each character is processed once.
- Space Complexity: O(n), as a new array is created to store capitalized words.
Code Snippet
Dry Run
Example input: "hello world"
- Step 1:
sentence.split(' ')
→ ['hello', 'world']
- Step 2: Capitalize each word:
"hello"
→ "Hello"
"world"
→ "World"
- Step 3: Join array →
"Hello World"
Final output: "Hello World"
Alternative Approach - Using Loop and Conditionals
Approach
We can manually capitalize each word by iterating through the characters of the string. For each word, capitalize the first character if it follows a space or is the start of the sentence.
Steps
- Initialize an empty string
result
and a capitalize
flag set to true
.
- Loop through each character in the string.
- If
capitalize
is true
, add the character as uppercase to result
and set capitalize
to false
.
- If the character is a space, add it to
result
and set capitalize
to true
to capitalize the next word.
- Otherwise, add the character as-is to
result
.
- Return
result
as the final capitalized sentence.
Time & Space Complexity
- Time Complexity: O(n), as each character is processed once.
- Space Complexity: O(n), since we create a new string.
Code Snippet
Dry Run
Example input: "hello world"
- Initialize:
result = ""
, capitalize = true
- Loop through
"hello world"
:
h
(capitalize) → result = "H"
, capitalize = false
e
, l
, l
, o
→ add as-is → result = "Hello"
- Space →
result = "Hello "
, capitalize = true
w
(capitalize) → result = "Hello W"
, capitalize = false
o
, r
, l
, d
→ add as-is → result = "Hello World"
- Final output:
"Hello World"
Complexity Analysis
JavaScript Method (Using String Methods)
- Time Complexity: O(n)
- Space Complexity: O(n)
Alternative Approach (Using Loop and Conditionals)
- Time Complexity: O(n)
- Space Complexity: O(n)
Conclusion
Capitalizing each word in a string can be efficiently achieved by splitting and mapping or by manually processing each character. Both approaches offer linear time complexity, but the split and map method is simpler to implement.