20 · String Parsing & Expression Evaluation

#68 Text Justification

Hardsolve on LeetCode ↗

frequently reported atAirbnbByteDance / TikTokUberAtlassianLinkedInGoogle

the problem

In plain words

Given a list of words and a width maxWidth, lay the words out as lines of exactly maxWidth characters. Put as many words on each line as fit, with at least one space between neighbours. Spread each line's spare spaces over its gaps as evenly as possible; when they don't divide evenly, the gaps on the left get one more. A line holding a single word, and the last line, are left-justified instead: one space between words, then spaces up to the width.

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

out ["This is an","example of text","justification. "]

Line 2 has 3 spare spaces for 2 gaps: the left gap gets 2, the right gets 1.

in words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16

out ["What must be","acknowledgment ","shall be "]

"acknowledgment" is alone on its line, so it is left-justified; so is the last line.

  • 1 ≤ words.length ≤ 300
  • 1 ≤ words[i].length ≤ 20, no spaces inside a word
  • words[i].length ≤ maxWidth ≤ 100

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #151
    2. #763
      Partition Labels
      Mediumin Greedy
    3. #271
      Encode and Decode Strings
      Mediumin ParsingLeetCode Premium