Text Justification
Given an array of words and a width max_width, format the text so that every line has exactly max_width characters and is fully justified. Return the lines as a list of strings.
Follow these rules:
- Pack each line greedily: fit as many words as possible, with at least one space between neighbors.
- Spread the extra spaces between the words as evenly as possible. When they don't divide evenly, the gaps on the left get one more space than the gaps on the right.
- A line with a single word is left-justified: the word, then spaces to fill the width.
- The last line is left-justified too: single spaces between words, then spaces to fill the width.
Example 1
Input: words = ["Keep", "the", "spacing", "even", "between", "words", "on", "each", "line."], max_width = 16 Output: [ "Keep the spacing", "even between", "words on each", "line. " ]
The third line has 5 spaces to share between 2 gaps, so the left gap gets 3 and the right gap gets 2. The last line is left-justified.
Example 2
Input: words = ["Short", "lines", "end", "here."], max_width = 11 Output: [ "Short lines", "end here. " ]
Constraints
1 <= words.length <= 3001 <= words[i].length <= 20words[i].length <= max_width <= 100- Each word contains only non-space characters.
Approach
There's no clever algorithm to find here. The difficulty is getting every rule right. Breaking the work into two steps per line keeps it manageable.
First, choose the words. Start a line with the next unused word, then keep adding words while the current width plus one space plus the next word still fits. Taking as many as fit is exactly what the rules ask for.
Then, lay out the line. If it's the last line or holds a single word, join the words with single spaces and pad the end. Otherwise, the line has gaps = words - 1 gaps and spaces = max_width - letters spaces to distribute. Every gap gets spaces // gaps, and the first spaces % gaps gaps get one more. That puts the extra spaces on the left, as required.
Steps
- Starting at word
i, extend the line to wordjwhile the next word fits after a single space. - If
jis past the last word or the line has one word, join with single spaces and pad the right side tomax_width. - Otherwise, compute
base = spaces // gapsandextra = spaces % gaps. - Build the line by giving each gap
basespaces, plus one more for the firstextragaps. - Add the line to the result, set
i = jand repeat until every word is used.
from typing import List
def full_justify(words: List[str], max_width: int) -> List[str]:
lines = []
i = 0
while i < len(words):
# Greedily take as many words as fit with at least one space between them.
j, width = i + 1, len(words[i])
while j < len(words) and width + 1 + len(words[j]) <= max_width:
width += 1 + len(words[j])
j += 1
line_words = words[i:j]
gaps = len(line_words) - 1
if j == len(words) or gaps == 0:
# Last line or a single word: left-justify and pad on the right.
line = " ".join(line_words)
lines.append(line + " " * (max_width - len(line)))
else:
spaces = max_width - sum(len(w) for w in line_words)
base, extra = divmod(spaces, gaps) # the first `extra` gaps get one more space
line = ""
for k, word in enumerate(line_words[:-1]):
line += word + " " * (base + (1 if k < extra else 0))
lines.append(line + line_words[-1])
i = j
return linesComplexity
- Time:
O(n * max_width). Each output line hasmax_widthcharacters, and there are at mostnlines. - Space:
O(n * max_width)for the output.
Common mistakes
- Giving the extra spaces to the rightmost gaps instead of the leftmost ones.
- Dividing by zero gaps on a line that holds a single word.
- Fully justifying the last line. It uses single spaces and pads on the right.
- Forgetting to count the single space before each new word when checking whether it fits.
You are given a string S and a number K as input, and your task is to print S to console output considering that, at most, you can print K characters per line.
Example: S = "abracadabra sample" K = 11
Output: abracadabra sample
Note that this problem requires the interviewee gather extra requirements from the interviewer (e.g. do we care about multiple white spaces? what if the length of a word is greater than K, ...)