Problem Description
Given a string that contains words interleaved with spaces, rearrange the spaces so that the spaces between each pair of adjacent words are equal and maximized. Any extra spaces that cannot be evenly distributed must be placed at the end of the string.
Key Insights
- Count the total number of spaces in the string.
- Extract words by splitting the string on spaces.
- If there is more than one word, compute the number of spaces between words (total spaces divided by (number of words - 1)).
- Compute any remaining spaces that cannot be evenly distributed.
- In the case of a single word, append all spaces after the word.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input string, since the string is processed once to count spaces and split words. Space Complexity: O(n), required for storing the split words and constructing the result string.
Solution
We use a two-step approach. First, we process the string to count the number of space characters and extract the words using a split operation. Second, we compute how many spaces should be placed between words and how many should be appended at the end. The evenly distributed spaces between words are achieved via integer division, while the remainder is appended as trailing spaces if more than one word is present. In the special case of a string containing only one word, all the counted spaces are appended at the end.