# 68. Text Justification

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:

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

Example 2:

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.

Example 3:

Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
         "to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]

# Solution

Approach 1: ...

# Code (Python)

Approach 1:

    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        if not words:
            return []
        start = 0
        result = []
        sum_min_lengths = 0
        for end in range(len(words)):
            sum_min_lengths += len(words[end])
            if start != end:
                sum_min_lengths += 1
            if sum_min_lengths > maxWidth:
                result.append(self.format_double(words, start, end - 1, maxWidth))
                start = end
                sum_min_lengths = len(words[end])
        if start < len(words):
            result.append(self.format_left(words, start, len(words) - 1, maxWidth))
        return result
    
    def format_double(self, words, start, end, width):
        if start == end:
            return self.format_left(words, start, end, width)
        whitespace_width = width - sum(map(len, words[start:end + 1]))
        whitespaces = [' ' * (whitespace_width // (end - start))] * (end - start)
        for i in range(whitespace_width % (end - start)):
            whitespaces[i] = whitespaces[i] + ' '
        result = [words[start]]
        for i in range(len(whitespaces)):
            result.append(whitespaces[i])
            result.append(words[start+i+1])
        return ''.join(result)
    
    def format_left(self, words, start, end, width):
        result = ' '.join(words[start:end + 1])
        return result + ' ' * (width - len(result))

# Code (C++)

Approach 1:

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> res;
        int head = 0;
        int tail = 1;
        int len = words[head].size() + 1;
        while (tail < words.size())
        {
            if (len + words[tail].size() > maxWidth)
            {
                int extraSpacesNr = maxWidth-len+1;
                int wordsNr = tail - head - 1;
                int extraSpaces = (wordsNr == 0) ? 0 : extraSpacesNr/wordsNr;
                int leftExtraSapces = (wordsNr == 0) ? 0 : extraSpacesNr%wordsNr;
                ostringstream oss;
                int tailSpaces = maxWidth;
                for (int i = head; i < tail-1; ++i)
                {
                    int spaces = extraSpaces + 1;
                    if (leftExtraSapces-- > 0)
                        spaces++;
                    oss << words[i] << string(spaces, ' ');
                    tailSpaces -= (words[i].size() + spaces);
                }
                tailSpaces -= words[tail-1].size();
                oss << words[tail-1] << string(tailSpaces, ' ');
                res.push_back(oss.str());
                head = tail;
                len = 0;
            }
            len += words[tail].size() + 1;
            tail++;
        }
        ostringstream oss;
        int tailSpaces = maxWidth;
        for (int i = head; i < tail - 1; ++i)
        {
            oss << words[i] << ' ';
            tailSpaces -= (words[i].size() + 1);
        }
        tailSpaces -= words[tail-1].size();
        oss << words[tail-1] << string(tailSpaces, ' ');
        res.push_back(oss.str());
        return res;
    }
};