Problem description:

Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

Note:

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word’s length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

Example 1:

1
2
3
4
5
6
7
Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Example 2:

1
2
3
4
5
6
7
8
9
Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified becase it contains only one word.

Solution:

(len(word) + chars + len(cur)) includes the space that need to add between words.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
ans, cur = [], []
chars = 0

for word in words:
# if cur is empty or the total chars + total needed spaces + next word fit
if not cur or (len(word) + chars + len(cur)) <= maxWidth:
cur.append(word)
chars += len(word)
else:
# place spaces, append the line to the ans, and move on
line = self.placeSpacesBetween(cur, maxWidth - chars)
ans.append(line)
cur.clear()
cur.append(word)
chars = len(word)

# left justify any remaining text, which is easy
if cur:
extra_spaces = maxWidth - chars - len(cur) + 1
ans.append(' '.join(cur) + ' ' * extra_spaces)

return ans


def placeSpacesBetween(self, words, spaces):
if len(words) == 1: return words[0] + ' ' * spaces

space_groups = len(words)-1
spaces_between_words = spaces // space_groups
extra_spaces = spaces % space_groups

cur = []
for word in words:
cur.append(word)

# place the min of remaining spaces or spaces between words plus an extra if available
cur_extra = min(1, extra_spaces)
spaces_to_place = min(spaces_between_words + cur_extra, spaces)

cur.append(' ' * spaces_to_place)

if extra_spaces: extra_spaces -= 1
spaces -= spaces_to_place

return ''.join(cur)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:

result, current_list, num_of_letters = [],[], 0
# result -> stores final result output
# current_list -> stores list of words which are traversed but not yet added to result
# num_of_letters -> stores number of chars corresponding to words in current_list

for word in words:

# total no. of chars in current_list + total no. of chars in current word
# + total no. of words ~= min. number of spaces between words
if num_of_letters + len(word) + len(current_list) > maxWidth:
# size will be used for module "magic" for round robin
# we use max. 1 because atleast one word would be there and to avoid modulo by 0
size = max(1, len(current_list)-1)

for i in range(maxWidth-num_of_letters):
# add space to each word in round robin fashion
index = i%size
current_list[index] += ' '

# add current line of words to the output
result.append("".join(current_list))
current_list, num_of_letters = [], 0

# add current word to the list and add length to char count
current_list.append(word)
num_of_letters += len(word)

# form last line by join with space and left justify to maxWidth using ljust (python method)
# that means pad additional spaces to the right to make string length equal to maxWidth
result.append(" ".join(current_list).ljust(maxWidth))

return result

time complexity: $O()$
space complexity: $O()$
reference:
related problem: