Leetcode 1592. Rearrange Spaces Between Words

Problem Explanation

The aim of the problem is to redistribute the spaces in a string such that every pair of adjacent words has an equal number of spaces between them and this number of spaces is maximized. If all the spaces can't be evenly distributed, we are required to place the remaining spaces at the end of the string.

To solve this problem we need to count the number of spaces and words in the string. Then we divide the total number of spaces by the number of words minus 1. We get how many spaces should be put between the words. If the division is not exact, the remainder is the number of spaces to put at the end of the string after we've distributed the spaces between the words.

Walkthrough of the Solution

The solution uses two standard library functions: count and istringstream.

count is a simple function that counts occurrences of a value in a container. Here we use it to count the number of spaces in text.

istringstream is a bit more complex. An istringstream is an input string stream, a kind of object that can be used just like cin, but instead of reading from the standard input it reads from a string you give it when you create it.

We store each word in the string in a vector.

Then we check if there's only one word in the string. In this case we just return that word concatenated with a number of spaces equal to the total spaces.

Then for each word except the last one, we add the word and the calculated number of spaces between words to the result string. Finally, we add the last word and the remainder of the spaces. Now the string is correctly formatted according to the problem's requirements, so we return it.

C++ Solution

1
2cpp
3class Solution {
4 public:
5  string reorderSpaces(string text) {
6    // count the number of spaces
7    const int spaces = count(begin(text), end(text), ' ');
8
9    vector<string> words;
10
11    istringstream iss(text);
12    string word;
13
14    // put each word in a vector
15    while (iss >> word)
16      words.push_back(word);
17
18    // if there's only one word in the string
19    if (words.size() == 1)
20      return word + string(spaces, ' ');
21
22    // calculate spaces between words and remainder
23    const int gapSize = spaces / (words.size() - 1);
24    const int remains = spaces % (words.size() - 1);
25
26    string ans;
27    
28    // append words and spaces to the answer string
29    for (int i = 0; i < words.size() - 1; ++i)
30      ans += words[i] + string(gapSize, ' ');
31      
32    ans += words.back() + string(remains, ' ');
33
34    return ans;
35  }
36};

Python Solution

1
2python
3class Solution:
4    def reorderSpaces(self, text: str) -> str:
5        # count the number of spaces
6        spaces = text.count(' ')
7        words = text.split()
8        
9        # if there's only one word in the string
10        if len(words) == 1:
11            return words[0] + ' ' * spaces
12        
13        # calculate spaces between words and remainder
14        gap_size = spaces // (len(words) - 1)
15        remains = spaces % (len(words) - 1)
16        
17        # append words and spaces to the answer string
18        return (' ' * gap_size).join(words) + ' ' * remains

Java Solution

1
2java
3import java.util.*;
4class Solution {
5    public String reorderSpaces(String text) {
6        // count the number of spaces
7        int spaces = 0;
8        for (char c : text.toCharArray()) {
9            if (c == ' ') spaces++;
10        }
11
12        String[] words = text.trim().split("\\s+");
13        
14        int gapSize = (spaces / (words.length - 1));
15        int remains = spaces % (words.length - 1);
16
17        String ans = "";
18        
19        for (int i = 0; i < words.length - 1; ++i) {
20            ans += words[i] + String.join("", Collections.nCopies(gapSize, " "));
21        }
22        ans += words[words.length - 1] + String.join("", Collections.nCopies(remains, " "));
23
24        return ans;
25    }
26}

JavaScript Solution

1
2javascript
3var reorderSpaces = function(text) {
4    let spaces = text.split('').filter(space => space === ' ').length
5    let words = text.trim().split(/\s+/);
6    
7    if (words.length === 1) {
8        return words[0] + ' '.repeat(spaces);
9    }
10    
11    let spacesBetween = Math.floor(spaces / (words.length - 1));
12    let remainder = spaces % (words.length - 1);
13    
14    return words.join(' '.repeat(spacesBetween)) + ' '.repeat(remainder);
15};

C# Solution

1
2csharp
3public class Solution {
4    public string ReorderSpaces(string text) {
5        int spaces = text.Count(c => c == ' ');
6        string[] words = text.Split(' ',StringSplitOptions.RemoveEmptyEntries);
7        
8        if (words.Length == 1) {
9            return words[0] + new string(' ', spaces);
10        }
11        
12        int spacesBetween = spaces / (words.Length - 1);
13        int remainder = spaces % (words.Length - 1);
14        
15        return String.Join(new string(' ', spacesBetween), words)+new string(' ', remainder);
16    }
17}

All the solutions provided in this article use a similar approach. First, they count the total number of spaces available in the text and the number of words. Then, they use the counts to calculate the number of spaces to be placed between words and the remaining spaces to put at the end of the string.

In Python and JavaScript, the entire line of text is split into words at every space, while in Java, the string is trimmed before being split. This removes leading and trailing spaces. However, all solutions account for the possibility of having only one word in the text.

Final words, this problem is a great exercise in manipulating strings in different languages and highlights the importance of using built-in string functions effectively. To solve such problems more efficiently, try to understand and memorize the string handling functions and libraries available in the programming language you're using.

For further practice, consider implementing these solutions in additional programming languages to further expand your coding expertise.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫