easy +8 pts

Replace multiple spaces

Collapse runs of whitespace into a single space in a given string.

Write a function `normalize_spaces(s: str) -> str` that takes a string and returns a new string where every sequence of one or more space characters (' ') is replaced by a single space. Leading and trailing spaces are also collapsed to a single space if present; otherwise, they are removed. Only the space character is considered; tabs and newlines are not treated as spaces. The function should work for any string, including empty strings and strings with no spaces.

Constraints

Length of `s` is between 0 and 10,000 characters. Only ASCII characters. Expected time complexity: O(n), where n is the length of the string. Expected space complexity: O(n) for the output.

Example

>>> normalize_spaces('Hello   world')
'Hello world'
>>> normalize_spaces('  multiple   spaces  ')
' multiple spaces '
>>> normalize_spaces(' no spaces')
' no spaces'
>>> normalize_spaces('')
''
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Scan the string and append a space only when you encounter a space that is not preceded by another space.
Alternatively, use a loop and check if the current character is a space and the previous character is not a space.
Think about how to handle the boundary at the start of the string.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.