Rearrange Spaces Between Words - String - Easy - LeetCode
💻 coding

Rearrange Spaces Between Words - String - Easy - LeetCode

2 min read 331 words
2 min read
ShareWhatsAppPost on X
  • 1The task is to rearrange spaces in a string so that they are evenly distributed between words.
  • 2If spaces cannot be evenly distributed, any remaining spaces are placed at the end of the string.
  • 3The algorithm has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to rearrange spaces in a string so that they are evenly distributed between words."

Rearrange Spaces Between Words - String - Easy - LeetCode

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. Example 3:

Input: text = "hello world" Output: "hello world" Example 4:

Input: text = " walks udp package into bar a" Output: "walks udp package into bar a " Example 5:

Input: text = "a" Output: "a"

Constraints:

1 <= text.length <= 100 text consists of lowercase English letters and ' '. text contains at least one word.

public class Solution {
 public string ReorderSpaces(string text) {
 int spaces = 0; 
 for(int i=0;i<text.Length;i++){
 if(text[i]==' '){
 spaces++;
 }
 }
 
 var arr = text.Split(' '); 
 var list = new List<string>();
 foreach(var item in arr){
 if(string.IsNullOrEmpty(item)){
 continue;
 }
 list.Add(item);
 }
 
 int equalSpaces = spaces;
 if(list.Count>1){
 equalSpaces = spaces/(list.Count-1); 
 }
 
 var sb = new StringBuilder();
 foreach(var item in list){
 sb.Append(item); 
 for(int i=0;i<equalSpaces && spaces > 0;i++){
 sb.Append(" ");
 spaces--;
 }
 }
 
 while(spaces>0){
 sb.Append(" ");
 spaces--;
 }
 
 return sb.ToString();
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 2 October 2020 · 2 min read · 331 words

Part of AskGif Blog · coding

You might also like