> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Text Justification Python Solution with Tests

> Tested Python solution for LeetCode 68 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 68, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [String](/catalog/topics/string), [Simulation](/catalog/topics/simulation). [View on LeetCode](https://leetcode.com/problems/text-justification/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 68   # by problem number
lcpy gen -s text_justification   # by problem name
```

## Problem

Given an array of strings `words` and a width `max_width`, format the text such that each line has exactly `max_width` 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 `max_width` characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does 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 `max_width`.
* The input array `words` contains at least one word.

### Examples

```
Input: words = ["This", "is", "an", "example", "of", "text", "justification."], max_width = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]
```

```
Input: words = ["What","must","be","acknowledgment","shall","be"], max_width = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
```

```
Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], max_width = 20
Output:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]
```

### Constraints

* 1 \<= words.length \<= 300
* 1 \<= words\[i].length \<= 20
* words\[i] consists of only English letters and symbols.
* 1 \<= max\_width \<= 100
* words\[i].length \<= max\_width

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/text_justification/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/text_justification/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(total characters)
    # Space: O(max_width) excluding the output list
    def full_justify(self, words: list[str], max_width: int) -> list[str]:
        result: list[str] = []
        line: list[str] = []
        line_length = 0

        for word in words:
            # +len(line) accounts for one joining space per existing word
            if line_length + len(line) + len(word) > max_width:
                # Justify the current line: distribute spaces across gaps,
                # assigning extra spaces to the leftmost gaps
                total_spaces = max_width - line_length
                gaps = len(line) - 1
                if gaps == 0:
                    result.append(line[0] + " " * total_spaces)
                else:
                    base, extra = divmod(total_spaces, gaps)
                    row_parts: list[str] = []
                    for i, w in enumerate(line[:-1]):
                        row_parts.append(w)
                        row_parts.append(" " * (base + (1 if i < extra else 0)))
                    row_parts.append(line[-1])
                    result.append("".join(row_parts))
                line = []
                line_length = 0

            line.append(word)
            line_length += len(word)

        # Last line: left-justified with single spaces, padded on the right
        result.append(" ".join(line).ljust(max_width))
        return result
```

## Complexity

| Time | Space |
| - | - |
| O(total characters) | O(max\_width) excluding the output list |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.