Skip to problem
←

Text Justification

Hard 0 attempts

Arrange words into lines of exactly maxWidth characters, preserving word order and spelling. Never split a word.

  1. Pack each line greedily with as many words as fit, allowing at least one space between adjacent words.
  2. For a nonfinal line with multiple words, distribute all remaining spaces between words as evenly as possible. Give any extra spaces to the leftmost gaps.
  3. For the final line, use exactly one space between words and pad the right side with spaces.
  4. For any single-word line, place all padding after the word.

Return an array of strings. Every line, including the last, must have exactly maxWidth characters. Trailing spaces are part of the answer.

For ["a","b","c","dddd"] at width 8, the first line is "a b c": its two gaps contain three and two spaces. The last line is "dddd ".

Function contract

Implement fullJustify(words, maxWidth).

Output: Return an array of lines, each exactly maxWidth characters long. Preserve every space, including trailing spaces on the last line and single-word lines.

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 = ["a"]
maxWidth = 3
Output
["a  "]
Constraints
  • 1 <= words.length <= 300
  • 1 <= maxWidth <= 100
  • 1 <= words[i].length <= min(20,maxWidth)
  • Words contain no spaces.

Greedy Line Packing + Space Distribution

When testing whether another word fits, include one required space for each existing word. Once the line is full, subtract the total word lengths from maxWidth to find the number of spaces.

For fully justified lines, divide that space count by the gap count. Each gap gets the quotient, and the leftmost remainder gaps get one extra. Handle final and single-word lines separately to avoid division by zero and preserve right padding.

javascript
function fullJustify(words, maxWidth) {
  const result = [];
  let i = 0;
  while (i < words.length) {
    let j = i,
      lineLen = 0;
    while (j < words.length && lineLen + words[j].length + (j - i) <= maxWidth)
      lineLen += words[j++].length;
    const numWords = j - i,
      numSpaces = maxWidth - lineLen;
    let line = words[i];
    if (numWords === 1 || j === words.length) {
      for (let k = i + 1; k < j; k++) line += ' ' + words[k];
      line += ' '.repeat(maxWidth - line.length);
    } else {
      const gaps = numWords - 1,
        spacePerGap = Math.floor(numSpaces / gaps),
        extra = numSpaces % gaps;
      for (let k = 1; k < numWords; k++)
        line += ' '.repeat(spacePerGap + (k <= extra ? 1 : 0)) + words[i + k];
    }
    result.push(line);
    i = j;
  }
  return result;
}

Time: O(C + W), where C is total input characters and W is total output characters | Space: O(W), including output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript