Algo-Sim › String Algorithms

Text Justification

Hard · String Algorithms · step through it in Java, Python and C++ on your own input

Pack words greedily into lines of maxWidth, spread the spare spaces left-heavy across the gaps, and left-justify the last line.

Problem

Given words and maxWidth, format the text so each line has exactly maxWidth characters and is fully justified. Pack as many words as fit on each line (greedily). Spread extra spaces as evenly as possible; when they don’t divide evenly, the left gaps get more. The last line, and any line with one word, is left-justified and padded with spaces on the right.

Constraints

Edge cases to test

Follow-up questions

Why do the left gaps get the extra spaces?
The task says so; with spaces = slack / gaps and slack % gaps extras, the first slack % gaps gaps take one more.
What if you want the prettiest layout, not the greedy one?
Minimise the sum of squared slack with a DP over line breaks (Knuth–Plass): O(n²).

Solution

Java

public List<String> fullJustify(String[] words, int maxWidth) {
    List<String> out = new ArrayList<>();
    int i = 0;
    while (i < words.length) {
        // Greedy: take words while they still fit with one space between each.
        int j = i, len = 0;
        while (j < words.length && len + words[j].length() + (j - i) <= maxWidth)
            len += words[j++].length();
        int gaps = j - i - 1, spaces = maxWidth - len;
        StringBuilder line = new StringBuilder();
        if (j == words.length || gaps == 0) {
            // Last line, or a single word: left-justify and pad the end.
            for (int k = i; k < j; k++) {
                line.append(words[k]);
                if (k < j - 1) line.append(' ');
            }
            while (line.length() < maxWidth) line.append(' ');
        } else {
            for (int k = i; k < j; k++) {
                line.append(words[k]);
                // The leftmost gaps get one extra space when it doesn't divide evenly.
                if (k < j - 1) line.append(" ".repeat(spaces / gaps + (k - i < spaces % gaps ? 1 : 0)));
            }
        }
        out.add(line.toString());
        i = j;
    }
    return out;
}

Python

def full_justify(words, max_width):
    out, i = [], 0
    while i < len(words):
        # Greedy: take words while they still fit with one space between each.
        j, length = i, 0
        while j < len(words) and length + len(words[j]) + (j - i) <= max_width:
            length += len(words[j])
            j += 1
        gaps, spaces = j - i - 1, max_width - length
        if j == len(words) or gaps == 0:
            # Last line, or a single word: left-justify and pad the end.
            line = " ".join(words[i:j])
            line += " " * (max_width - len(line))
        else:
            line = ""
            for k in range(i, j):
                line += words[k]
                if k < j - 1:
                    # The leftmost gaps get one extra space when it doesn't divide evenly.
                    line += " " * (spaces // gaps + (1 if k - i < spaces % gaps else 0))
        out.append(line)
        i = j
    return out

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<string> fullJustify(vector<string> &words, int maxWidth) {
        vector<string> out;
        int i = 0, n = words.size();
        while (i < n) {
            // Greedy: take words while they still fit with one space between each.
            int j = i, len = 0;
            while (j < n && len + int(words[j].size()) + (j - i) <= maxWidth)
                len += words[j++].size();
            int gaps = j - i - 1, spaces = maxWidth - len;
            string line;
            if (j == n || gaps == 0) {
                // Last line, or a single word: left-justify and pad the end.
                for (int k = i; k < j; k++) {
                    line += words[k];
                    if (k < j - 1) line += ' ';
                }
                line += string(maxWidth - line.size(), ' ');
            } else {
                for (int k = i; k < j; k++) {
                    line += words[k];
                    // The leftmost gaps get one extra space when it doesn't divide evenly.
                    if (k < j - 1) line += string(spaces / gaps + (k - i < spaces % gaps ? 1 : 0), ' ');
                }
            }
            out.push_back(line);
            i = j;
        }
        return out;
    }
};

More String Algorithms problems