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

# 68 Text Justification

Given an array of words and a lengthL, format the text such that each line has exactlyLcharacters 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 exactlyLcharacters.

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.

For example,\
**words**:`["This", "is", "an", "example", "of", "text", "justification."]`\
**L**:`16`.

Return the formatted lines as:

```
[
   "This    is    an",
   "example  of text",
   "justification.  "
]
```

**Note:**&#x45;ach word is guaranteed not to exceedLin length.

**Nearly working:**

* It seems to me that many of the rules are too arbitrary, with many edge cases.

```python
import math


def normalize_text(current_words, max_width):
    """
    :type current_words: List[str]
    :type max_width: int
    :rtype: string
    """
    if (len(current_words) == 1):
        return current_words[0] + " " * (abs(max_width - len(current_words[0])))

    # accumulate the total length of the array
    cumulative_len = 0
    for word in current_words:
        cumulative_len += len(word)

    left_over_spaces = abs(max_width - cumulative_len)

    # divide the spaces evenly between the words
    # -1 in order to not account for the last word
    spaces_per_word = left_over_spaces / (len(current_words) - 1)
    discrete_spaces_per_word = int(spaces_per_word)

    iter = 0
    # add set amount of spaces, dicluding the last word
    while (iter < len(current_words) - 1):
        current_words[iter] += (" " * discrete_spaces_per_word)
        iter += 1

    # add the remaining bits spread equally through all the words
    remaining_spaces = left_over_spaces - (discrete_spaces_per_word * (len(current_words) - 1))
    word_iter = 0
    while (remaining_spaces > 0):
        wrapper = word_iter % len(current_words)
        current_words[wrapper] +=  " "
        word_iter += 1
        remaining_spaces -= 1

    # now append to single string
    cum_str = ""
    for word in current_words:
        cum_str += word

    return cum_str


def fullJustify(words, maxWidth):
    """
    :type words: List[str]
    :type maxWidth: int
    :rtype: List[str]['']
    """
    if (len(words) == 0 or words[0] == ''):
        return [' ' * maxWidth];

    justified_text = []
    row_string = []
    cur_width = 0
    iter = 0

    while (iter < len(words)):
        # +1 to account for additional space after word
        # except for the last word
        if (iter + 1 < len(words) and cur_width + len(words[iter]) + 1 < maxWidth):
            cur_width += len(words[iter]) + 1
        else:
            cur_width += len(words[iter])

        if (cur_width > maxWidth):
            justified_text.append(normalize_text(row_string, maxWidth))

            # consider previously ignored word
            iter -= 1
            row_string = []
            cur_width = 0

        else:
            row_string.append(words[iter])

        iter += 1

    # edge case: next iteration may contain data
    if (len(row_string) > 0):
        justified_text.append(normalize_text(row_string, maxWidth))
    return justified_text


print(fullJustify(["What","must","be","shall","be."], 12))
print(fullJustify(["a","b","c","d","e"], 1))
print(fullJustify(["a"], 1))
print(fullJustify([""], 0))
print(fullJustify([""], 2))
print(fullJustify(["This", "is", "an", "example", "of", "text", "justification."], 16))
```


---

# 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://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/68-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.
