Rearrange Spaces Between Words - Problem

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.

Input & Output

Example 1 — Multiple Words with Extra Spaces
$ Input: text = " this is a sentence "
Output: "this is a sentence"
💡 Note: 9 total spaces distributed among 3 gaps = 3 spaces per gap with 0 remainder
Example 2 — Uneven Distribution
$ Input: text = " hello world "
Output: "hello world"
💡 Note: 5 total spaces with 1 gap = 5 spaces between words, no remainder
Example 3 — Single Word
$ Input: text = " hello "
Output: "hello "
💡 Note: Single word case: all 4 spaces go at the end after the word

Constraints

  • 1 ≤ text.length ≤ 100
  • text consists of lowercase English letters and spaces ' '
  • text contains at least one word

Visualization

Tap to expand
Rearrange Spaces Between Words INPUT Original String (25 chars): _ _ t h i s _ _ _ i s _ _ a _ s e n t e n c e _ _ = Space (9 total) = Letter Extracted Words: this is a sentence Statistics: Total spaces: 9 Word count: 4 Gaps needed: 3 text = " this is a sentence " // 25 characters total ALGORITHM STEPS 1 Count Spaces Loop through text, count ' ' spaces = 9 2 Extract Words Use split() to get words ["this","is","a","sentence"] 3 Calculate Distribution Divide spaces among gaps gaps = 4 - 1 = 3 spacesPerGap = 9 / 3 = 3 extraSpaces = 9 % 3 = 0 4 Build Result Join words with spaces separator = " " // 3 spaces result = words.join(separator) FINAL RESULT Rearranged String (25 chars): t h i s _ _ _ i s _ _ _ a _ _ _ s e n t e n c e = Equal spaces (3 each) Space Distribution: this [3] is [3] a [3] sentence 9 spaces / 3 gaps = 3 per gap Extra spaces: 0 OK - No trailing spaces needed Output: "this is a sentence" // 25 chars (same length) OK - Valid Result
Asked in
Facebook 15 Microsoft 12
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending

Select Compiler

Choose a programming language

Compiler list would appear here...

AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tab to accept Esc to dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.