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:
0 and not exceed maxWidth.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 <= 3001 <= words[i].length <= 20words[i] consists of only English letters and symbols.1 <= maxWidth <= 100words[i].length <= maxWidthWhen 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:
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:
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_outputInstead 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:
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| Case | How to Handle |
|---|---|
| A single word whose length is equal to maxWidth | 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 | 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 | 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 | 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 | 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 | 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 | The greedy approach packs up to maxWidth words per line and assigns single spaces between them correctly. |