Rearrange Spaces Between Words
text has words separated by one or more spaces, and may have spaces at its ends. Redistribute the spaces so that equal numbers of spaces separate each pair of neighbouring words, as many as possible. Any spaces that cannot be shared evenly go at the end. If there is only one word, all spaces go after it. The length of the result equals the length of text.
Example 1
text " this is a sentence "
returns "this is a sentence"
9 spaces, 3 gaps: 3 spaces each, nothing left over.
Example 2
text "a b c d"
returns "a b c d "
4 spaces among 3 gaps: 1 each and 1 left over at the end.
Constraints
1 <= len(text) <= 100- Lowercase letters and spaces, at least one word
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.