/68. Text Justification

68. Text Justification

Hard
Arrays50.6% acceptance

Given a list of strings word_list and an integer line_width, format the text such that each line has exactly line_width characters and is fully justified. Words should be packed greedily, fitting as many as possible per line. Extra spaces should be distributed as evenly as possible between words; if uneven, assign more spaces to the leftmost slots. The last line should be left-justified, with no extra space between words. Return the formatted lines as a list of strings.

Example 1

Input: word_list = [Alpha, Beta, Gamma, Delta], line_width = 12

Output: [Alpha Beta, Gamma Delta]

Explanation: First line: Alpha and Beta with 2 spaces between. Second line: Gamma Delta left-justified.

Example 2

Input: word_list = [One, Two, Three, Four, Five], line_width = 10

Output: [One Two, Three Four, Five ]

Explanation: Last line is left-justified with trailing spaces.

Constraints

  • 1 <= len(word_list) <= 300
  • 1 <= len(word) <= 20 for word in word_list
  • Each word contains only English letters and symbols
  • 1 <= line_width <= 100
  • len(word) <= line_width for word in word_list
Python (current runtime)

Case 1

Input: word_list = ['A', 'B', 'C', 'D'], line_width = 5

Expected: ['A B C', 'D ']

Case 2

Input: word_list = ['Hello', 'World', 'Python'], line_width = 11

Expected: ['Hello World', 'Python ']

Case 3

Input: word_list = ['abc', 'def', 'ghi', 'jkl'], line_width = 9

Expected: ['abc def', 'ghi jkl']

Case 4

Input: word_list = ['x', 'y', 'z'], line_width = 3

Expected: ['x y', 'z ']