Capitalize First and Last Character of Each Word
Problem
You are given a string s made up of words separated by single spaces. Each word contains only lowercase English letters. Return a new string in which, for every word, the first and the last character are converted to uppercase while every other character stays unchanged. Words of length 1 have the same first and last character, so that single character becomes uppercase.
Input / Output
- Input: a string
swith1 <= s.length <= 10^5, words separated by exactly one space, no leading or trailing spaces. - Output: the transformed string.
Examples
Example 1
Input: s = "hello world"
Output: "HellO WorlD"
Explanation: In hello the first letter h and the last letter o become uppercase. Same for world.
Example 2
Input: s = "a quick brown fox"
Output: "A QuicK BrowN FoX"
Explanation: The single-letter word a becomes A.
Example 3
Input: s = "abc"
Output: "AbC"
Constraints
1 <= s.length <= 10^5scontains only lowercase letters and spaces.- There is exactly one space between consecutive words.
Approach
This is a straightforward string-scanning problem, but interviewers use it to check whether you can handle boundaries cleanly without splitting the string into a list (which costs extra memory).
- Convert the string to a mutable character array.
- Walk through the array with an index
i. A character at indexiis the first letter of a word ifi == 0ors[i-1] == ' '. It is the last letter of a word ifi == n-1ors[i+1] == ' '. - If either condition holds and the character is a letter, replace it with its uppercase form.
- Join the characters back into a string.
Because each position is inspected once and the checks are constant time, the algorithm is linear.
Alternative: split on spaces, transform each word (w[0].upper() + w[1:-1] + w[-1].upper() with a guard for length 1) and join with a single space. This is simpler to write but allocates a list of words.
Complexity
- Time: O(n), where n is the length of the string.
- Space: O(n) for the output (O(1) extra if the language allows in-place mutation).
Follow-ups often asked
- Handle multiple consecutive spaces or leading/trailing spaces without collapsing them.
- Do it in place in a language with mutable strings (C/C++).
- Extend to Unicode words where "letter" is not just
a–z.
Reference solution (Python)
def capitalize_ends(s: str) -> str:
chars = list(s)
n = len(chars)
for i, c in enumerate(chars):
if c == ' ':
continue
first = i == 0 or chars[i - 1] == ' '
last = i == n - 1 or chars[i + 1] == ' '
if first or last:
chars[i] = c.upper()
return ''.join(chars)
Test cases
| Input | Expected |
|---|---|
"hello world" | "HellO WorlD" |
"a quick brown fox" | "A QuicK BrowN FoX" |
"x" | "X" |
"ab" | "AB" |