68. Text Justification

Explanation:

To solve this problem, we can follow these steps:

  1. Iterate over the words list and greedily form lines by adding words until the line length exceeds the maxWidth.
  2. Calculate the total number of spaces required to evenly distribute among words in each line.
  3. Handle the special case when there is only one word in a line or it is the last line.
  4. Construct the final result by formatting the lines with appropriate spaces.

Time Complexity: O(N), where N is the total number of characters in all words.

Space Complexity: O(N), where N is the total number of characters in all words.

:

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> result = new ArrayList<>();
        int start = 0;
        
        while (start < words.length) {
            int end = start + 1;
            int lineLength = words[start].length();
            
            while (end < words.length && lineLength + words[end].length() + (end - start) <= maxWidth) {
                lineLength += words[end].length();
                end++;
            }
            
            int spaces = maxWidth - lineLength;
            int gaps = end - start - 1;
            
            StringBuilder sb = new StringBuilder();
            sb.append(words[start]);
            
            if (gaps == 0 || end == words.length) {
                for (int i = start + 1; i < end; i++) {
                    sb.append(" ").append(words[i]);
                }
                for (int i = sb.length(); i < maxWidth; i++) {
                    sb.append(" ");
                }
            } else {
                int spacesPerGap = spaces / gaps;
                int extraSpaces = spaces % gaps;
                
                for (int i = start + 1; i < end; i++) {
                    for (int j = 0; j < spacesPerGap; j++) {
                        sb.append(" ");
                    }
                    if (extraSpaces > 0) {
                        sb.append(" ");
                        extraSpaces--;
                    }
                    sb.append(words[i]);
                }
            }
            
            result.add(sb.toString());
            start = end;
        }
        
        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.