Update appNew update is available. Click here to update.

Justify Text

Last Updated: 14 Jan, 2021
Difficulty: Hard

PROBLEM STATEMENT

Try Problem

Given a sentence(in the form of an array of words), and an integer ‘L’, return an array of strings i.e a paragraph such that each line has exactly ‘L’ characters, and is left and right justified.

Justification of text means that space is added between words so that both edges of each line are aligned with both margins. The last line in the paragraph is aligned left.

One needs to add the maximum number of words in a line such that the number of lines is minimised.

We can add whitespaces in a line so that each line has exactly the same number of characters i.e L.

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.

For example:
Let the given sentence be: [ “what”, “must”, “be”, “shall”, “be.”]
And L=12.

The justified output will be :

[ “what must be”
“Shall be.”       ]

Note that the last line is only left justified.
Input Format:
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.
The first line of each test case contains a single integer ‘n’ denoting the number of words in the sentence.
The second line of each test case contains space separated strings denoting the word in the sentence. Note that no word has space in between it.
The third line of each test case contains the integer ‘L’ denoting the number of characters in each line in the justified output
Output Format:
For each test case, return an array of strings denoting the justified output of the given sentence.
The output for each test case is in a separate line.
Note:
1. You do not need to print anything; it has already been taken care of.
2. The words do not contain whitespaces.
3. It is guaranteed that L is always greater than the number of characters in any of the given words in the given array ‘words’