Capitalise the first letter of every word in a sentence without title(), lower-casing the rest. String building in Python with split and join, tested.
The problem
Return sentence with the first letter of each word upper-cased and the rest of the word lower-cased. Words are separated by single spaces. Don't use str.title().
Examples
Example 1
Input
capitalize_words('hello world')Expected output
'Hello World'
Example 2
Input
capitalize_words('pYTHON iS fun')Expected output
'Python Is Fun'
+ 3 hidden tests on Submit — title() would give It'S.
Edge cases to ask about
- Apostrophes
- Empty string
- Mixed case
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Per-word slice + join | O(n) | O(n) | w[:1] is safe on empty words. |
Walkthrough of the optimal approach (try it yourself first)
Split into words, rebuild each as first.upper() + rest.lower(), and join with spaces. w[:1] (not w[0]) avoids an IndexError on empty words.
"it's".title() gives "It'S" because title() starts a new word after the apostrophe — that is why interviewers ask you to write it yourself.
Complexity: O(n) time, O(n) space. Every character is copied once into the new string.
Reveal the reference solution
def capitalize_words(sentence): return " ".join(w[:1].upper() + w[1:].lower() for w in sentence.split(" "))
Follow-ups interviewers ask
- Keep runs of multiple spaces intact.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Capitalise the First Letter of Each Word in Python?
The optimal solution runs in O(n) time and O(n) auxiliary space. Every character is copied once into the new string.
What follow-up questions do interviewers ask about Capitalise the First Letter of Each Word?
Keep runs of multiple spaces intact.
