Rearrange Spaces Between Words – C++ Solution


class Solution {
 public:
  string reorderSpaces(string text) {
    const int spaces = ranges::count(text, ' ');
    string ans;
    vector words;

    istringstream iss(text);
    string word;

    while (iss >> word)
      words.push_back(word);

    if (words.size() == 1)
      return word + string(spaces, ' ');

    const int gapSize = spaces / (words.size() - 1);
    const int remains = spaces % (words.size() - 1);

    for (int i = 0; i < words.size() - 1; ++i)
      ans += words[i] + string(gapSize, ' ');
    ans += words.back() + string(remains, ' ');

    return ans;
  }
};
    

Problem Description

Ah, the classic "Rearrange Spaces Between Words" problem! It’s like trying to organize a messy room where your friends have left their shoes everywhere, and you just want to make it look presentable. The task is simple: given a string of words separated by spaces, you need to rearrange those spaces so that they are evenly distributed between the words. If there are leftover spaces, they should be added to the end of the string.

Imagine you’re at a party, and everyone is standing too close together. You want to create some space between them, but you also want to make sure that no one feels left out. That’s exactly what this problem is about!

Approach

The approach taken in this solution is straightforward yet effective. First, we count the total number of spaces in the input string. Then, we extract the words from the string using a string stream. If there’s only one word, we simply append all the spaces to the end of that word.

If there are multiple words, we calculate the size of the gaps between the words and distribute the spaces evenly. Any remaining spaces are added to the end of the string. This ensures that the words are nicely spaced out, just like a well-organized party!

Time and Space Complexity

Time Complexity

O(n), where n is the length of the input string. We traverse the string to count spaces and extract words.

Space Complexity

O(m), where m is the number of words in the string. We store the words in a vector.

Real-World Example

Think of a classroom where students are sitting too close together. The teacher wants to rearrange the desks to create a more comfortable learning environment. By moving the desks apart and ensuring that there’s equal space between them, the teacher creates a better atmosphere for learning. Similarly, the "Rearrange Spaces Between Words" problem helps us create a more visually appealing string by distributing spaces evenly.

Similar Problems

  • 3-Sum Solution in C++
  • 4-Sum Solution in C++