Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on core interview patterns fundamentals.
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 <= 100text consists of lowercase English letters and ' '.text contains at least one word.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
" this is a sentence "
" practice makes perfect"
text-justification)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1592: Rearrange Spaces Between Words
class Solution {
public String reorderSpaces(String text) {
int spaces = 0;
for (char c : text.toCharArray()) {
if (c == ' ') {
++spaces;
}
}
String[] words = text.trim().split("\\s+");
if (words.length == 1) {
return words[0] + " ".repeat(spaces);
}
int cnt = spaces / (words.length - 1);
int mod = spaces % (words.length - 1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; ++i) {
sb.append(words[i]);
if (i < words.length - 1) {
sb.append(" ".repeat(cnt));
}
}
sb.append(" ".repeat(mod));
return sb.toString();
}
}
// Accepted solution for LeetCode #1592: Rearrange Spaces Between Words
func reorderSpaces(text string) string {
cnt := strings.Count(text, " ")
words := strings.Fields(text)
m := len(words) - 1
if m == 0 {
return words[0] + strings.Repeat(" ", cnt)
}
return strings.Join(words, strings.Repeat(" ", cnt/m)) + strings.Repeat(" ", cnt%m)
}
# Accepted solution for LeetCode #1592: Rearrange Spaces Between Words
class Solution:
def reorderSpaces(self, text: str) -> str:
spaces = text.count(" ")
words = text.split()
if len(words) == 1:
return words[0] + " " * spaces
cnt, mod = divmod(spaces, len(words) - 1)
return (" " * cnt).join(words) + " " * mod
// Accepted solution for LeetCode #1592: Rearrange Spaces Between Words
impl Solution {
pub fn reorder_spaces(text: String) -> String {
let spaces = text.chars().filter(|&c| c == ' ').count();
let words: Vec<&str> = text.split_whitespace().collect();
if words.len() == 1 {
return format!("{}{}", words[0], " ".repeat(spaces));
}
let cnt = spaces / (words.len() - 1);
let mod_spaces = spaces % (words.len() - 1);
let result = words.join(&" ".repeat(cnt));
result + &" ".repeat(mod_spaces)
}
}
// Accepted solution for LeetCode #1592: Rearrange Spaces Between Words
function reorderSpaces(text: string): string {
const spaces = (text.match(/ /g) || []).length;
const words = text.split(/\s+/).filter(Boolean);
if (words.length === 1) {
return words[0] + ' '.repeat(spaces);
}
const cnt = Math.floor(spaces / (words.length - 1));
const mod = spaces % (words.length - 1);
const result = words.join(' '.repeat(cnt));
return result + ' '.repeat(mod);
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.