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.

Thought Process

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

Last updated