Given a string str and width of each line as L, the task is to justify the string such that each line of justified text is of length L with help of space (‘ ‘) and the last line should be left-justified.
Input: str = “GeeksforGeek is the best computer science portal for geeks.”, L = 16
Input: str = “The quick brown fox jumps over the lazy dog.”, L = 11
The symbol _ denotes a space.
The number of spaces between words in each line cannot be computed until a complete set of words in that line is known. We will solve this problem on a line-by-line basis.
- Split the given text into words
- Firstly select the words which can be inserted in each line including a space between each word. For that, the sum of length of included words with one space between them must be smaller than or equal to L.
- Now count the number of spaces needed to make the length of each line L and distribute the spaces evenly.
- Repeat above steps for next set of words.
- For the last line spaces must be assigned at the end as the last line must be left-justified.
Below is the implementation of the above approach:
GeeksforGeek is the best computer science portal for geeks.
Time Complexity: O(N), where N = length of string
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.