Problem overview
The method capitalizeWords receives a string sentence and returns it with the first letter of each word in upper case. Words are separated by single spaces, and the sentence neither starts nor ends with a space. Only the first character of each word changes. The rest of the word stays exactly as it was, even if it contains capitals, and a first character without an upper case, such as a digit, stays as it is.
"hello world" becomes "Hello World". "learn to code with AlgoCademy" becomes "Learn To Code With AlgoCademy", since AlgoCademy already starts with a capital. "iPhone and NASA" becomes "IPhone And NASA": only the first character of each word is touched.
Approach
Break the problem into three pieces: cut the sentence into words, fix each word, and glue the words back together. Strings are immutable in TypeScript, so the method builds new strings rather than editing the old one.
split(" ") cuts a string at every space and returns an array of the pieces. Each word is rebuilt as its first character in upper case followed by everything after the first character. The fixed words go into a new array, in order. join(" ") then puts a single space between them, which recreates the original spacing, since the original had exactly one space between words.
Step by step
- Split the sentence with
sentence.split(" ")intowords, astring[]. - Declare
resultas an emptystring[]. It collects the fixed words in the same order. - Loop over the words with
for (const word of words). - Build
capitalized:word[0].toUpperCase()is the first character in upper case, andword.slice(1)is the rest. Adding them with+concatenates the strings. - Push
capitalizedontoresult. - Return
result.join(" ")to glue the words together with one space between each two.
The solution in TypeScript
class Solution {
capitalizeWords(sentence: string): string {
let words: string[] = sentence.split(" ");
let result: string[] = [];
for (const word of words) {
const capitalized: string = word[0].toUpperCase() + word.slice(1);
result.push(capitalized);
}
return result.join(" ");
}
}
word[0]is a one-character string. TypeScript has no separate character type, sotoUpperCase()is a string method that works on it.toUpperCase()leaves other characters alone. For a digit it returns the digit:"3d"[0].toUpperCase()is"3", so"3d"stays"3d".slice(1)starts at index 1 and goes to the end. On a one-letter word it returns an empty string, so"a"becomes"A"with nothing added.- The result array and the original are separate.
toUpperCasedoesn't modify the word; it returns a new string, and the originalsentenceis unchanged. - Types are erased.
string[]andstringdon't exist at run time.
Complexity
Time: O(n), where n is the length of the sentence. Splitting, copying each word with slice and joining each touch every character a constant number of times.
Space: O(n). The array of words, the result array and the final string each hold about n characters in total.
Edge cases and common mistakes
- One word.
"hello"gives"Hello":splitreturns an array of one element. - One-letter words.
"a b 3d"gives"A B 3d". - Capitals inside a word.
"NASA"stays"NASA"and"iPhone"becomes"IPhone". Lower-casing the rest of each word would break both. - Double spaces. The lesson guarantees single spaces. With two in a row,
split(" ")produces an empty string between them,word[0]isundefinedand callingtoUpperCase()on it throws aTypeError. Code that has to accept such input would need to skip empty words. - Changing the word in place. Writing
word[0] = "H"can't work: the compiler reports that the index only permits reading, and in strict-mode code the assignment throws aTypeError. Build a new string instead. - Joining with nothing.
join("")would run the words together. The separator" "restores the spaces.
Testing
sentence = "hello world"gives"Hello World".sentence = "learn to code with AlgoCademy"gives"Learn To Code With AlgoCademy".sentence = "iPhone and NASA"gives"IPhone And NASA".sentence = "a b 3d"gives"A B 3d".
