Text Justification

Given an array of words, A and a width B, format the text such that each line has exactly B 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 hashes ’#’ when necessary so that each line has exactly B characters.

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

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

Return the final formatted strings.

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 B.
  • The input array words contains at least one word.


Input Format:

The first argument of input contains an array of strings, A.
The second argument of input contains an integer, B.

Output Format:

Return an array of strings containing the formatted strings.

Constraints:
1 <= length(A) <= 2e5
1 <= B <= 2e5

Examples:

Input 1:
    A = ["This", "is", "an", "example", "of", "text", "justification."]
    B = 16
    
Output 1:
    [  "This####is####an", "example##of#text", "justification.##"   ]

Input 2:
    
    A = ["What","must","be","acknowledgment","shall","be"]
    B = 16

Output 2:
    ["What###must###be", "acknowledgment##", "shall#be########"    ]
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Text Justification on Interview Code Editor
Hints
  • Hints are not available for this problem

Discussion


Loading...
Click here to start solving coding interview questions