KatInterview

68. Text Justification

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to format a given array of words into lines of text, where each line has a specific maximum width. The core challenge lies in implementing the two types of justification required:

Solution

Text Justification in Python

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        result = []
        i = 0
        n = len(words)

        while i < n:
            # Step 1: Find the words that can fit in the current line.
            j = i
            line_length = 0
            # j - i is the number of minimum spaces required
            while j < n and line_length + len(words[j]) + (j - i) <= maxWidth:
                line_length += len(words[j])
                j += 1
            
            num_words = j - i
            total_spaces = maxWidth - line_length

            # Step 2: Format the line based on the case.
            # Case A: Last line or a line with a single word (left-justified).
            if num_words == 1 or j == n:
                line = " ".join(words[i:j])
                line += " " * (maxWidth - len(line))
                result.append(line)
            else:
                # Case B: Fully justified line.
                num_gaps = num_words - 1
                spaces_per_gap = total_spaces // num_gaps
                extra_spaces = total_spaces % num_gaps

                line = []
                for k in range(i, j):
                    line.append(words[k])
                    if k < j - 1:
                        spaces_to_apply = spaces_per_gap + (1 if extra_spaces > 0 else 0)
                        line.append(" " * spaces_to_apply)
                        extra_spaces -= 1
                
                result.append("".join(line))

            i = j # Move to the start of the next line.
        
        return result

Text Justification in Java

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> result = new ArrayList<>();
        int i = 0;
        int n = words.length;

        while (i < n) {
            // Step 1: Find the words that can fit in the current line.
            int j = i;
            int lineLength = 0;
            // j - i is the number of minimum spaces required
            while (j < n && lineLength + words[j].length() + (j - i) <= maxWidth) {
                lineLength += words[j].length();
                j++;
            }

            StringBuilder line = new StringBuilder();
            int numWords = j - i;
            int totalSpaces = maxWidth - lineLength;

            // Step 2: Format the line based on the case.
            // Case A: Last line or a line with a single word (left-justified).
            if (numWords == 1 || j == n) {
                for (int k = i; k < j; k++) {
                    line.append(words[k]);
                    if (k < j - 1) {
                        line.append(' ');
                    }
                }
                // Pad the rest of the line with spaces.
                while (line.length() < maxWidth) {
                    line.append(' ');
                }
            } else {
                // Case B: Fully justified line.
                int numGaps = numWords - 1;
                int spacesPerGap = totalSpaces / numGaps;
                int extraSpaces = totalSpaces % numGaps;

                for (int k = i; k < j; k++) {
                    line.append(words[k]);
                    if (k < j - 1) {
                        int spacesToApply = spacesPerGap + (extraSpaces-- > 0 ? 1 : 0);
                        for (int s = 0; s < spacesToApply; s++) {
                            line.append(' ');
                        }
                    }
                }
            }
            result.add(line.toString());
            i = j; // Move to the start of the next line.
        }

        return result;
    }
}

Text Justification in C++

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> result;
        int i = 0;
        int n = words.size();

        while (i < n) {
            // Step 1: Find the words that can fit in the current line.
            int j = i;
            int lineLength = 0;
            while (j < n && lineLength + words[j].length() + (j - i) <= maxWidth) {
                lineLength += words[j].length();
                j++;
            }

            string line = "";
            int numWords = j - i;
            int totalSpaces = maxWidth - lineLength;

            // Step 2: Format the line based on the case.
            // Case A: Last line or a line with a single word (left-justified).
            if (numWords == 1 || j == n) {
                line += words[i];
                for (int k = i + 1; k < j; ++k) {
                    line += ' ' + words[k];
                }
                line += string(maxWidth - line.length(), ' ');
            } else {
                // Case B: Fully justified line.
                int numGaps = numWords - 1;
                int spacesPerGap = totalSpaces / numGaps;
                int extraSpaces = totalSpaces % numGaps;

                line += words[i];
                for (int k = i + 1; k < j; ++k) {
                    line += string(spacesPerGap, ' ');
                    if (extraSpaces > 0) {
                        line += ' ';
                        extraSpaces--;
                    }
                    line += words[k];
                }
            }
            result.push_back(line);
            i = j; // Move to the start of the next line.
        }

        return result;
    }
};

Text Justification in TypeScript

function fullJustify(words: string[], maxWidth: number): string[] {
    const result: string[] = [];
    let i = 0;
    const n = words.length;

    while (i < n) {
        // Step 1: Find the words that can fit in the current line.
        let j = i;
        let lineLength = 0;
        // j - i is the number of minimum spaces required
        while (j < n && lineLength + words[j].length + (j - i) <= maxWidth) {
            lineLength += words[j].length;
            j++;
        }

        let line = '';
        const numWords = j - i;
        const totalSpaces = maxWidth - lineLength;

        // Step 2: Format the line based on the case.
        // Case A: Last line or a line with a single word (left-justified).
        if (numWords === 1 || j === n) {
            line = words.slice(i, j).join(' ');
            line += ' '.repeat(maxWidth - line.length);
        } else {
            // Case B: Fully justified line.
            const numGaps = numWords - 1;
            const spacesPerGap = Math.floor(totalSpaces / numGaps);
            let extraSpaces = totalSpaces % numGaps;

            for (let k = i; k < j; k++) {
                line += words[k];
                if (k < j - 1) {
                    const spacesToApply = spacesPerGap + (extraSpaces > 0 ? 1 : 0);
                    line += ' '.repeat(spacesToApply);
                    extraSpaces--;
                }
            }
        }
        result.push(line);
        i = j; // Move to the start of the next line.
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.