Coding problem · Easy · Basics

Capitalize Each Word

Easy Algorithms & data structures

Given a sentence s of lower-case words separated by single spaces, return it with the first letter of each word in upper case.

Example 1

Input: s = "hello world"
Output: "Hello World"

Example 2

Input: s = "ready camel learns fast"
Output: "Ready Camel Learns Fast"

Hints

Hint 1

Split the sentence into words.

Hint 2

Upper-case the first character of each word, keep the rest, then join with spaces.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(n)

Split on spaces, transform each word (word[0].toUpperCase() + word.slice(1)), and join the words back together.

Reference solution

function capitalizeWords(s) {
  return s.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
}

Was this page helpful?