~/coding-interview/leetcode-rearrange-space-between-words.md

Leetcode - Rearrange Spaces Between Words

// TL;DR

Count total spaces, split into words, divide spaces evenly between word gaps. Remainder spaces go at the end. Edge case: one word gets all spaces appended.

Leetcode - Rearrange Spaces Between Words

Problem Statement

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

Input: text = "  this   is  a sentence "
Output: "this   is   a   sentence"

Input: text = " practice   makes   perfect"
Output: "practice   makes   perfect "

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

Solution

You need to have three things to solve this problem:

  1. Number of words
  2. The actual words
  3. Number of spaces

If you have 4 words, and 9 spaces. You will put 9 / (4-1) = 3 spaces in between.

Lets look at the algorithm:

  • First get the number of words, number of spaces, and the words
  • Calculate how many spaces you will put in between words
  • Calculate how many remainder spaces you will need to put after final string
  • There are some special conditions when
    • there is only spaces
    • there is one word and none or few spaces

Code

Lets look at the code now

private int process(String text, List<String> words) {
  int spaces = 0;
  
  for (int i=0; i<text.length(); ) {
    if (text.charAt(i) == ' ') {
      while (i < text.length() && text.charAt(i) == ' ') {
        spaces ++;
        i++;
      }
    }
    else {
      StringBuilder sb = new StringBuilder();
      while (i < text.length() && text.charAt(i) != ' ') {
        sb.append(text.charAt(i));
        i++;
      }
      if (sb.length() > 0) {
        words.add(sb.toString());
      }
    }
  }
  
  return spaces;
}

public String reorderSpaces(String text) {
  List<String> words = new ArrayList<String>();
  int spaces = this.process(text, words);
  
  int divider = (words.size() - 1) > 0 ? (words.size() - 1) : 1;
  
  int targetSpaces = spaces / divider;
  int remainingSpaces = spaces % divider;
  if (words.size()<= 1) {
    remainingSpaces += targetSpaces;
  }
  
  StringBuilder sb = new StringBuilder();
  if (words.size() > 0) {
    sb.append(words.get(0));
  }
  for (int i=1; i<words.size(); i++) {
    for (int j=0; j<targetSpaces; j++) {
      sb.append(" ");
    }
    sb.append(words.get(i));
  }
  
  if (remainingSpaces > 0) {
    for (int j=0; j<remainingSpaces; j++) {
      sb.append(" ");
    }
  }
  
  return sb.toString();
}

Complexity

Its O(n)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Replace all spaces in a string with %20

Replace all spaces in a string with %20

Problem Statement Replace all spaces in a string with ‘%20’ (three characters…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…