# Text Justification

## Problem

Given an array of words and a width *maxWidth*, format the text such that each line has exactly *maxWidth* 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 spaces `' '` when necessary so that each line has exactly *maxWidth* characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do 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.

**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 *maxWidth*.
* The input array `words` contains at least one word.

![](https://1063826111-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGdx41c9p2PMgIHbUTK%2F-MR0iO0nBSzWHSfccFtS%2F-MR0jtjUFqXSETFHZnYD%2FScreen%20Shot%202021-01-14%20at%209.34.26%20AM.png?alt=media\&token=96de4451-07c8-4112-9eb0-cff0f13284dc)

![](https://1063826111-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGdx41c9p2PMgIHbUTK%2F-MR0iO0nBSzWHSfccFtS%2F-MR0jz98LdmaGp_y3fPv%2FScreen%20Shot%202021-01-14%20at%209.34.48%20AM.png?alt=media\&token=2ec4005c-6c44-4bcd-89df-709d7d402525)

### Thought Process

![](https://1063826111-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGdx41c9p2PMgIHbUTK%2F-MR0iO0nBSzWHSfccFtS%2F-MR0o4ZeQrbQibE8hG3a%2FIMG_CC95EB369CA5-1.jpeg?alt=media\&token=ee86f54c-9baf-414a-af77-ab5c53c48980)

![](https://1063826111-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGdx41c9p2PMgIHbUTK%2F-MR0iO0nBSzWHSfccFtS%2F-MR0oOIy6dS4ZWT_kF9H%2FIMG_A308A6C98E4C-1.jpeg?alt=media\&token=20f37d83-7b5d-4b05-8c41-c800fbfb003c)

## Solution

```
# we don't want it to be <= maxWidth because if it does == maxWidth 
# then when we apply the extra space for the neew 
# word the line will be over maxWidth


class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        result = []
        n = len(words)
        
        i=0
        while i < n:
            lineLength = len(words[i])
            j = i+1
            
            while j < n and (lineLength + len(words[j]) + (j-i-1) < maxWidth):
                lineLength+=len(words[j])
                j+=1
            
            wordCount = (j-i)
            spacesNeeded = maxWidth - lineLength
            
            if wordCount == 1 or j >= n:
                result.append(self.leftAlign(words, i,j, spacesNeeded))
            else:
                result.append(self.middleAlign(words, i,j, spacesNeeded))
                
            i = j
            
                
        return result
    
    
    def middleAlign(self, words, i, j, spacesNeeded):
        spaceSections = j-i-1
        spacesPerSection = (spacesNeeded//spaceSections)
        extraSpaces = (spacesNeeded%spaceSections)
        res = ""
        res+=words[i]
        
        for k in range(i+1, j):
            applySpaces = 0
            if extraSpaces > 0:
                applySpaces = spacesPerSection + 1
                extraSpaces-=1
            else:
                applySpaces = spacesPerSection
            
            res+=(" " * applySpaces) + words[k]
            
        return res
    
    def leftAlign(self, words, i, j, spacesNeeded):
        rightSpaces = spacesNeeded - (j-i-1)
        res=""
        res+=words[i]
        
        for k in range(i+1, j):
            res+=" " + words[k]
            
        res+=(" " * rightSpaces)
        
        return res
        
```

## Time Complexity

* **Time**: O(lines \* maxWidth)
* **Space:** O(lines \* maxWidth) for result array


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/strings/string-simulation/text-justification.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
