Program to rearrange spaces between words in Python

Sometimes we need to rearrange spaces between words to create uniform spacing. This involves redistributing all spaces evenly between words, with any extra spaces placed at the end.

Given a string with words separated by varying numbers of spaces, we need to rearrange the spaces so that there are equal spaces between every pair of adjacent words. If we cannot redistribute all spaces equally, the extra spaces go at the end.

Example

If the input is " I love programming ", the output will be "I love programming ". The original string has 9 spaces total, which gets distributed as 4 spaces between each pair of words, with 1 extra space at the end.

Algorithm

To solve this problem, we follow these steps ?

  • Count total spaces in the string

  • Extract words using split()

  • If only one word exists, append all spaces to the end

  • Calculate spaces per gap: total_spaces รท (word_count - 1)

  • Build result by joining words with calculated spaces

  • Add remaining spaces at the end

Implementation

def solve(s):
    res = ""
    total_sp = s.count(" ")
    suff_sp_cnt = total_sp
    
    text_array = s.split()
    num_words = len(text_array)
    
    # Handle single word case
    if num_words == 1:
        res = text_array[0] + total_sp * " "
        return res
    
    # Calculate spaces between words
    sep_size = total_sp // (num_words - 1)
    sep = sep_size * " "
    
    # Build result string
    for i in text_array[:-1]:  # All except last word
        res += i
        res += sep
        suff_sp_cnt -= sep_size
    
    # Add last word
    res += text_array[-1]
    
    # Add remaining spaces at the end
    res += suff_sp_cnt * " "
    
    return res

# Test the function
s = " I love programming "
result = solve(s)
print(f"Input: '{s}'")
print(f"Output: '{result}'")
print(f"Total spaces: {s.count(' ')} -> {result.count(' ')}")
Input: ' I love programming '
Output: 'I    love    programming '
Total spaces: 9 -> 9

How It Works

The algorithm works by first counting all spaces (9 total) and extracting words. With 3 words, we have 2 gaps between them. Dividing 9 spaces by 2 gaps gives 4 spaces per gap with 1 remainder. The remainder goes at the end.

Edge Cases

# Single word
print(f"Single word: '{solve('  hello  ')}'")

# Two words  
print(f"Two words: '{solve(' a   b ')}'")

# Multiple spaces
print(f"Multiple: '{solve('  python    is    great  ')}'")
Single word: 'hello    '
Two words: 'a   b'
Multiple: 'python      is      great  '

Conclusion

This solution redistributes spaces evenly between words using integer division and handles remainders by placing extra spaces at the end. The time complexity is O(n) where n is the string length.

Updated on: 2026-03-25T20:22:26+05:30

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements