Problem statement

https://binarysearch.com/problems/Justify-Text/

Solution

Variation of Leetcode 0068. Text Justification.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, words, maxWidth):
        buffer, curr_len = [words[0]], len(words[0])
        ans = []

        def line(empty, places, buffer):
            a, b = divmod(empty, places)
            for i in range(places): buffer[i] += " "*a
            for i in range(b): buffer[i] += " "
            return buffer

        for i, word in enumerate(words[1:]):
            if curr_len + len(word) + 1 <= maxWidth:
                buffer.append(word)
                curr_len += len(word) + 1
            else:
                empty = maxWidth - curr_len + len(buffer) - 1
                places = len(buffer) - 1
                if places == 0: 
                    ans.append(buffer[0] + " "*(maxWidth - len(buffer[0])))
                else:
                    line(empty, places, buffer)
                    ans.append("".join(buffer))
                buffer, curr_len = [word], len(word)

        if len(buffer) > 1:
            line(maxWidth - curr_len + len(buffer) - 1, len(buffer) - 1, buffer)
        t = "".join(buffer)
        return ans + [t + " "*(maxWidth - len(t))]