Text Justification

Hard · Arrays & Strings · about 35 minutes

Asked at Airbnb, Google, Robinhood, ByteDance, Apple, Bloomberg, Goldman Sachs, Citadel, Jane Street, Hudson River Trading, Plaid, Ramp, Chime, SoFi, Revolut, D. E. Shaw, Optiver, Yelp, Brex, Mercury, Kraken, Jump Trading, Susquehanna (SIG).

Lay out the list words as a block of lines, each exactly maxWidth characters wide, aligned on both sides.

  • Fill each line greedily: take as many words as fit with at least one space between neighbors.
  • Distribute the leftover spaces between the words as evenly as you can; when they can't be split evenly,

the gaps further left receive the extra spaces.

  • A line holding just one word sits at the left and is padded with trailing spaces.
  • The final line is aligned left: single spaces between words, padding at the end.

No word is longer than maxWidth.