Normalize Sentence Spacing

Easy
0/40
0 upvote

Problem statement

You are given a string s, which may contain words, extra spaces between words, and leading or trailing spaces.

Your task is to reformat the string to a "normalized" version. A normalized string has all its words separated by exactly one space, with no spaces at the beginning or end of the string.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains a single string s.


Output Format:
Print the reformatted string on a single line.


Note:
A "word" is defined as any sequence of non-space characters.

If the input string is empty or contains only spaces, the output should be an empty string.
Sample Input 1:
Hello   World  


Sample Output 1:
Hello World


Explanation for Sample 1:
The leading spaces, trailing spaces, and the multiple spaces between "Hello" and "World" are all collapsed into a single space separating the two words.


Sample Input 2:
Programming   is fun and    challenging  


Sample Output 2:
Programming is fun and challenging


Explanation for Sample 2:
All extra whitespace is removed, leaving only single spaces between each word.


Expected Time Complexity:
The expected time complexity is O(N), where N is the length of the string.


Constraints:
0 <= length of s <= 10^6
The string consists of letters and spaces.

Time limit: 1 sec
Approaches (1)
Normalize Sentence Spacing
Time Complexity

The expected time complexity is O(N), where N is the length of the string.

Space Complexity
Code Solution
(100% EXP penalty)
Normalize Sentence Spacing
Full screen
Console