> For the complete documentation index, see [llms.txt](https://joshualbarb.gitbook.io/leetcode-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://joshualbarb.gitbook.io/leetcode-problems/strings/string-simulation/text-justification.md).

# 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.

![](/files/-MR0jtjUFqXSETFHZnYD)

![](/files/-MR0jz98LdmaGp_y3fPv)

### Thought Process

![](/files/-MR0o4ZeQrbQibE8hG3a)

![](/files/-MR0oOIy6dS4ZWT_kF9H)

## 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
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
