Text Justification

Solution Code
class Solution:
    def fullJustify(self, words: list[str], maxWidth: int) -> list[str]:
        res, i = [], 0
        while i < len(words):
            line_words = []
            line_len = 0
            while i < len(words) and line_len + len(words[i]) + len(line_words) <= maxWidth:
                line_words.append(words[i])
                line_len += len(words[i])
                i += 1
            if i == len(words) or len(line_words) == 1:
                last_line = " ".join(line_words)
                res.append(last_line + " " * (maxWidth - len(last_line)))
            else:
                total_spaces = maxWidth - line_len
                gaps = len(line_words) - 1
                base_spaces = total_spaces // gaps
                extra_spaces = total_spaces % gaps
                for j in range(gaps):
                    line_words[j] += " " * (base_spaces + (1 if j < extra_spaces else 0))
                res.append("".join(line_words))
        return res

Time Complexity

O(N)

Space Complexity

O(N)