VOOZH about

URL: https://www.geeksforgeeks.org/dsa/justify-the-given-text-based-on-the-given-width-of-each-line/

⇱ Text Justification - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Text Justification

Last Updated : 23 Aug, 2024

Given an array of strings arr[] and a width W, format the text so each line has exactly W characters, left and right justified. Place as many words as possible per line, distribute extra spaces as evenly as possible, and assign more spaces to the left if they don't divide evenly. The last line should be left-justified with no extra spaces between words.

Examples:

Input: arr[] = {"GfG", "is", "the", "best", "computer", "science", "portal", "for", "geeks."}, W = 16
Output:
{
"GfG  is the best",
"computer science",
"portal       for",
"geeks.          "
}
Explanation: We need to justify the text such that each line has exactly 16 characters and should be equally justified.

  • Total characters in first line: "GfG" (3) + "is" (2) + "the" (3) + "best" (4) = 12 (including spaces: 12 + 3 = 15). Since, we need 1 more space and all the extra spaces should be added from left to right, we add 1 extra space between "GfG" and "is".
  • Total characters in second line: "computer" (8) + "science" (7) = 15 (including spaces: 15 + 1 = 16). No need to add extra spaces.
  • Total characters in third line: "portal" (6) + "for" (3) = 9 (including spaces = 9 + 1 = 10). Since, we need to add 6 extra spaces, we will add them between "portal" and "for".
  • Total characters in fourth line: "geeks." (6) = 6. Since we need 10 extra spaces and the last line should be left justified, we will add them at the end.

Input: arr[] = {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."}, W = 11
Output:
{
"The   quick",
"brown   fox",
"jumps  over",
"the    lazy",
"dog.       "
}

Approach:

The idea is to first select the words that can be inserted in each line including a single space between every pair of words. After selecting the words for each line, we need to justify the line.

To justify a line, the sum of length of included words with one space between them should be less than or equal to W. Also, if the current line is the last line of the text, then we need to append spaces to make the width of line equal to W. Otherwise, if the current line is not the last line then count the number of spaces needed to make the length of each line W and distribute the spaces evenly.

Below is the implementation of the approach: 


Output
GFG is the best
computer science
portal for
geeks. 

Time Complexity: O(N), where N is the sum of length of all words.
Auxiliary Space: O(W), where W is the max width of a line.

Comment