Given an array of strings 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 does 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.


&nbsp;
Example 1:

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

Example 2:

Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
Output:
[
&nbsp; "What &nbsp; must &nbsp; be",
&nbsp; "acknowledgment &nbsp;",
&nbsp; "shall be &nbsp; &nbsp; &nbsp; &nbsp;"
]
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 because 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:
[
&nbsp; "Science &nbsp;is &nbsp;what we",
  "understand &nbsp; &nbsp; &nbsp;well",
&nbsp; "enough to explain to",
&nbsp; "a &nbsp;computer. &nbsp;Art is",
&nbsp; "everything &nbsp;else &nbsp;we",
&nbsp; "do &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"
]

&nbsp;
Constraints:


	1 &lt;= words.length &lt;= 300
	1 &lt;= words[i].length &lt;= 20
	words[i] consists of only English letters and symbols.
	1 &lt;= maxWidth &lt;= 100
	words[i].length &lt;= maxWidth


class Solution:
    def fullJustify(self, words: List[str], maxwidth: int) -> List[str]:
        curr = 0
        last = []
        res = []
        for i in words:
            if curr + len(i) + len(res) <= maxwidth:
                curr += len(i)
                res.append(i)
            else:
                last.append(res)
                curr = len(i)
                res = [i]
        last.append(res)
        ans = []
        for idx ,row in enumerate(last):
            x = maxwidth-len("".join(row))
            t = len(row)-1
            if t == 0:
                ans.append(row[0] + " "*(x))
            elif idx != len(last)-1:
                spaces = x//t
                rem = x%t
                res = row[0]
                for i in row[1:]:
                    temp = spaces
                    if rem:
                        temp += 1
                        rem -= 1
                    res = res + " "*temp + i
                    # print(res, temp)
                ans.append(res)
            else:
                res = row[0]
                for i in row[1:]:
                    res = res + ' '+i
                res = res + " "*(maxwidth-len(res))
                ans.append(res)

        return ans
class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> unBalanced = new ArrayList<>();
        List<String> balanced = new ArrayList<>();
        int numSpaces = 0;

        StringBuffer sb = new StringBuffer();
        //Following code creates a list of unbalanced lines by appending words and 1 space between them
        for(String word : words){

            if(sb.length() == 0){
                sb.append(word);
            }else{
                if(sb.length() + 1 + word.length() <= maxWidth){
                    sb.append(" "+word);
                }else{
                    unBalanced.add(sb.toString());
                    sb = new StringBuffer(word);
                }
            }

        }

        if(sb.length() >0){
            unBalanced.add(sb.toString());
        }

        for(int j = 0; j < unBalanced.size(); j++){
            String line = unBalanced.get(j);
            numSpaces = maxWidth - line.length();
            StringBuffer lineB = new StringBuffer(line);
            //This if block handles either last line or the scenario where in there's only one word in any sentence and hence no spaces
            if(j == unBalanced.size()-1 || !line.contains(" ")){
                int tempSpaces = maxWidth - lineB.length();
                while(tempSpaces > 0){
                    lineB.append(" ");
                    tempSpaces --;
                }
                balanced.add(lineB.toString());
                continue;
            };
            // The following block checks for each character and appends 1 space during each loop
            //If there are still spaces left at the end of the String, again start from beggining and append spaces after each word
            while(numSpaces > 0){
                int i = 0;
                while(i < lineB.length() - 1){
                    if( lineB.charAt(i) == ' ' && lineB.charAt(i+1) != ' '){
                        lineB.insert(i+1, ' ');
                        i++;
                        numSpaces --;
                        if(numSpaces == 0) break;
                    }
                    i++;
                }
            }
            balanced.add(lineB.toString());
        }

        return balanced;
    }
}
class Solution {
    string preprocessing(string &f, int space, int limit)
    {
        int noofspace = limit-f.size()+space;
        int k = 0;
        string r = "";
        while(space)
        {
            int n = noofspace / space;
            if((noofspace%space) != 0)
                n += 1;
            noofspace -= n;
            while(f[k] != ' ')
            {
                r += f[k];
                k++;
            }
            k++;
            while(n--)
            {
                r += ' ';
            }
            space--;
        }
        while(k < f.size())
        {
            r += f[k];
            k++;
        }
        while(noofspace--)
            r += ' ';
        return r;
    }
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> ans;
        string f = "";
        int space = 0;
        for(string &str : words)
        {
            if((f.size() + str.size() + 1) <= maxWidth && f.size() > 0)
            {
                f += ' ' + str;
                space++;
            }
            else
            {
                if(f.size() > 0){
                    f = preprocessing(f, space, maxWidth);
                    ans.push_back(f);
                    f = "";
                }
                f += str;
                space = 0;
            }
        }
        int sz = f.size();
        while(sz < maxWidth)
        {
            f += ' ';
            sz++;
        }
        ans.push_back(f);
        return ans;
    }
};
/**
 * @param {string[]} words
 * @param {number} maxWidth
 * @return {string[]}
 */
var fullJustify = function(words, maxWidth) {
    if (!words || !words.length) return;
    
    const wordRows = [];
    let wordCols = [];
    let count = 0;
    words.forEach((word, i) => {
        if ((count + word.length + wordCols.length) > maxWidth) {
            wordRows.push(wordCols);
            wordCols = [];
            count = 0;
        }
        
        wordCols.push(word);
        count += word.length;

        if (i === words.length - 1) {
            wordRows.push(wordCols);
        }        
    });
    
    return wordRows.map((rowWords, i) => justifyText(rowWords, maxWidth, i === wordRows.length - 1));
};

const justifyText = (rowWords, maxWidth, isLastLine) => {
    let spaces = maxWidth - rowWords.reduce((acc, curr) => acc + curr.length, 0);
    
    if (rowWords.length === 1) {
        return rowWords[0] + ' '.repeat(spaces);        
    }
    
    if (isLastLine) {
        spaces -= rowWords.length - 1
        return rowWords.join(' ') + ' '.repeat(spaces);        
    }
    
    let index = rowWords.length - 1;
    let justifiedWord = '';
    while (rowWords.length > 0) {
        const repeater = Math.floor(spaces / (rowWords.length - 1));
        const word = rowWords.pop();

        if (index === 0) {
            justifiedWord = word + justifiedWord;
        } else if (index === 1) {
            justifiedWord = ' '.repeat(spaces) + word + justifiedWord;
        } else {
            justifiedWord = ' '.repeat(repeater) + word + justifiedWord;
        }
        
        index--;
        spaces -= repeater;
    }

    return justifiedWord;
}
Text Justification