Taro Logo

Text Justification

#2 Most AskedHard
168 views
Topics:
ArraysStrings

Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left-justified, and no extra space is inserted between words.

Note:

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

Example 1:

Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Example 2:

Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.

Example 3:

Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
Output:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]

Constraints:

  • 1 <= words.length <= 300
  • 1 <= words[i].length <= 20
  • words[i] consists of only English letters and symbols.
  • 1 <= maxWidth <= 100
  • words[i].length <= maxWidth

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we do if a single word in the `words` array has a length greater than `maxWidth`?
  2. For the last line of text, how should the trailing spaces be padded to reach the `maxWidth`?
  3. If a line contains multiple words but can only fit spaces such that they cannot be distributed evenly, how should the remainder spaces be distributed from left to right?
  4. Can the input `words` array be empty, and if so, what should be returned?
  5. Are all strings in `words` guaranteed to consist solely of alphabetic characters without any internal spaces?

Brute Force Solution

Approach

Imagine you have a box of words and need to arrange them into neat lines of a specific width. The brute force strategy involves testing every conceivable combination of word groupings until you find the exact layout that satisfies all spacing rules.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the first word and consider all the possible ways to group it with following words on the top line.
  2. For each possible group that fits within the width limit, figure out every possible way to pad the spaces between the words.
  3. Once you have a valid first line, move down to the remaining words and test every possible grouping for the second line.
  4. Continue this exhaustive trial-and-error process, building line after line until every single word has been placed.
  5. Whenever you reach the end of the words, check if the entire arrangement follows all the special spacing rules, especially for the final line.
  6. Keep a record of every valid arrangement you generate during this massive search.
  7. Finally, compare all the successful arrangements and pick the one that matches the desired formatted output.

Code Implementation

def full_justify(word_list, max_width):
    # We recursively explore all grouping combinations to evaluate every valid layout possibility.
    def generate_layouts(word_index):
        if word_index == len(word_list):
            return [[]]
        
        valid_layouts = []
        line_length = len(word_list[word_index])
        next_word_index = word_index + 1
        
        while next_word_index <= len(word_list) and line_length <= max_width:
            current_group = word_list[word_index:next_word_index]
            remaining_layouts = generate_layouts(next_word_index)
            for layout in remaining_layouts:
                valid_layouts.append([current_group] + layout)
                
            if next_word_index < len(word_list):
                line_length += 1 + len(word_list[next_word_index])
            next_word_index += 1
            
        return valid_layouts

    all_possible_layouts = generate_layouts(0)
    best_formatted_output = None
    
    # We test every generated layout group to find the one satisfying all line spacing rules.
    for layout_group in all_possible_layouts:
        formatted_lines = []
        is_layout_valid = True
        
        for line_index, line_words in enumerate(layout_group):
            is_last_line = (line_index == len(layout_group) - 1)
            word_count = len(line_words)
            total_chars = sum(len(word) for word in line_words)
            
            if word_count == 1 or is_last_line:
                joined_line = " ".join(line_words)
                padded_line = joined_line + " " * (max_width - len(joined_line))
                formatted_lines.append(padded_line)
            else:
                total_spaces = max_width - total_chars
                space_slots = word_count - 1
                base_spaces = total_spaces // space_slots
                extra_spaces = total_spaces % space_slots
                
                current_line_parts = []
                for word_idx in range(word_count - 1):
                    current_line_parts.append(line_words[word_idx])
                    spaces_to_add = base_spaces + (1 if word_idx < extra_spaces else 0)
                    current_line_parts.append(" " * spaces_to_add)
                current_line_parts.append(line_words[-1])
                formatted_lines.append("".join(current_line_parts))
                
        if is_layout_valid:
            best_formatted_output = formatted_lines
            break
            
    return best_formatted_output

Big(O) Analysis

Time Complexity
O(2^n) – To find the optimal line layout, the algorithm tests every conceivable combination of word groupings and space padding configurations across all available words. For a total of n words, the recursive trial-and-error process branches at each word to evaluate whether to include it in the current line or start a new one. This exhaustive search generates an exponential number of possible line arrangements before selecting the final output. The total operations therefore approximate a growth rate proportional to 2^n, which simplifies to O(2^n).
Space Complexity
O(n) – The brute-force trial-and-error search requires keeping a record of every valid arrangement generated during the massive search of word groupings and spacing combinations. As the number of words increases, the temporary data structures storing these intermediate formatted line arrangements and final output collections grow linearly with the input size N. Additionally, variables tracking the current line groups and recursive states consume auxiliary memory proportional to the total words. Therefore, the total extra memory required simplifies to Big O of N.

Optimal Solution

Approach

Instead of scrambling words randomly, the optimal strategy builds the final document line by line by packing as many words as possible into each row. Once a row is full, it calculates the exact spacing needed to stretch the words so that both margins line up neatly.

Here's how the algorithm would work step-by-step:

  1. Look at the beginning of the text and gather as many words as you can until adding one more would exceed the maximum width allowed for a single line.
  2. Once you have the group of words for the current line, figure out how many empty spaces are left over after writing the words.
  3. Distribute those leftover spaces evenly in the gaps between the words so the text stretches cleanly from margin to margin.
  4. Handle any uneven leftover spaces by placing the extra ones starting from the left side.
  5. Move down to the next row and repeat the exact same packing and spacing process for the remaining words.
  6. Treat the very final line of text as a special case by simply placing the words with a single space between them and pushing all remaining whitespace to the very end of the line.
  7. Continue this process until all words from the original text have been neatly placed into formatted lines.

Code Implementation

def full_justify(word_list, max_width):
    formatted_lines = []
    word_index = 0
    total_words = len(word_list)

    while word_index < total_words:
        line_start_index = word_index
        current_line_length = len(word_list[word_index])
        word_index += 1

        while word_index < total_words and current_line_length + 1 + len(word_list[word_index]) <= max_width:
            current_line_length += 1 + len(word_list[word_index])
            word_index += 1

        number_of_words = word_index - line_start_index
        
        # We identify the last line to apply left-alignment instead of full justification.
        if word_index == total_words or number_of_words == 1:
            single_spaced_line = " ".join(word_list[line_start_index:word_index])
            trailing_spaces = max_width - len(single_spaced_line)
            formatted_lines.append(single_spaced_line + " " * trailing_spaces)
            continue

        total_characters_length = sum(len(word_list[i]) for i in range(line_start_index, word_index))
        total_spaces_needed = max_width - total_characters_length
        number_of_gaps = number_of_words - 1

        base_space_width = total_spaces_needed // number_of_gaps
        extra_space_count = total_spaces_needed % number_of_gaps

        current_constructed_line = ""
        for gap_index in range(number_of_gaps):
            current_constructed_line += word_list[line_start_index + gap_index]
            # Extra spaces are distributed from the left to handle uneven remainders fairly.
            spaces_to_add = base_space_width + (1 if gap_index < extra_space_count else 0)
            current_constructed_line += " " * spaces_to_add

        current_constructed_line += word_list[word_index - 1]
        formatted_lines.append(current_constructed_line)

    # Returning the fully justified lines ensures the document meets formatting constraints.
    return formatted_lines

Big(O) Analysis

Time Complexity
O(n) – To justify the text, the algorithm iterates through the list of n words to pack them into lines and then processes those same n words again when constructing the spacing for each row. The total cost is driven by visiting each word a constant number of times during the line-building and space-distribution phases. This linear progression of operations across all words approximates a total cost proportional to 2n. Therefore, dropping the constant factor simplifies the overall runtime complexity to O(n).
Space Complexity
O(n) – To determine the space complexity, let N represent the total number of characters across all words in the input array. The algorithm allocates a result list of strings to store the fully justified lines, which in total hold all N characters plus the required padding spaces. Additionally, temporary string builders or arrays are used to gather words for each individual line before formatting. These intermediate data structures and the final output container scale linearly with the total input size, leading to an auxiliary space complexity of O(N).

Edge Cases

A single word whose length is equal to maxWidth
How to Handle:
The greedy packer naturally fits the word on its own line and left-justifies it without adding extra spaces.
A single word whose length is less than maxWidth
How to Handle:
The line is treated as the last line or a single-word line, so it gets padded with trailing spaces on the right.
The last line contains multiple words
How to Handle:
The algorithm explicitly checks if the line is the final one and left-justifies it with single spaces between words and trailing spaces at the end.
A line has only one word but is not the last line
How to Handle:
The space distribution logic identifies that there is only one word and pads the remainder of the line with spaces on the right.
Uneven distribution of extra spaces among multiple words
How to Handle:
Modulo arithmetic is used to distribute extra spaces one-by-one from left to right until all remaining spaces are accounted for.
maxWidth is very large relative to the word lengths
How to Handle:
The line packer packs as many words as possible into the current buffer before calculating spaces, regardless of how large the total width is.
All words have a length of 1 and maxWidth is small
How to Handle:
The greedy approach packs up to maxWidth words per line and assigns single spaces between them correctly.
0/57 completed