Rearrange Spaces Between Words Problem
Description
LeetCode Problem 1592.
You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.
Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.
Return the string after rearranging the spaces.
Example 1:
Input: text = " this is a sentence "
Output: "this is a sentence"
Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.
Example 2:
Input: text = " practice makes perfect"
Output: "practice makes perfect "
Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.
Constraints:
1 <= text.length <= 100textconsists of lowercase English letters and' '.textcontains at least one word.
Solution
Approach: Count and Rebuild
Count the spaces in text and split it into words. With w words there are w - 1 gaps:
- If there is only one word, there are no gaps, so all spaces go after it. This case needs its own branch, because dividing by
w - 1would divide by zero. - Otherwise each gap gets
spaces / (w - 1)spaces, and the remainderspaces % (w - 1)goes at the end.
Join the words with the gap and append the leftover spaces. The result has the same length as text, since every space is used exactly once.
Complexity: O(n) time and O(n) extra space for the words and the result.
class Solution:
def reorderSpaces(self, text: str) -> str:
spaces = text.count(" ")
words = text.split()
if len(words) == 1:
return words[0] + " " * spaces # no gaps: every space goes to the end
gap, extra = divmod(spaces, len(words) - 1)
return (" " * gap).join(words) + " " * extra