1+ from typing import List , Union , Collection , Mapping , Optional
2+ from abc import ABC , abstractmethod
3+
4+ class Solution :
5+ def fullJustify (self , words : List [str ], maxWidth : int ) -> List [str ]:
6+ """
7+ Performs text justification by distributing words and spaces across lines of fixed width.
8+
9+ Strategy: Build lines word by word until adding the next word would exceed maxWidth.
10+ When a line is full, distribute extra spaces evenly using round-robin.
11+ """
12+ result = [] # Final list of justified lines
13+ current_list = [] # Words being accumulated for the current line
14+ num_of_letters = 0 # Total character count (excluding spaces) in current_list
15+
16+ for word in words :
17+ # Check if adding this word exceeds the line width
18+ # Formula: letters + new_word_length + minimum_spaces_needed
19+ # Minimum spaces = one space between each word = len(current_list)
20+ if num_of_letters + len (word ) + len (current_list ) > maxWidth :
21+ # Justify and add the current line to results
22+
23+ # Calculate number of gaps between words (n words = n-1 gaps)
24+ # Use max(1, ...) to handle single-word lines and avoid division by zero
25+ num_gaps = max (1 , len (current_list ) - 1 )
26+
27+ # Distribute extra spaces using round-robin
28+ # Total spaces needed = maxWidth - num_of_letters
29+ extra_spaces = maxWidth - num_of_letters
30+ for i in range (extra_spaces ):
31+ # Use modulo to cycle through gaps repeatedly
32+ # This ensures spaces are distributed as evenly as possible
33+ gap_index = i % num_gaps
34+ current_list [gap_index ] += ' '
35+
36+ # Join words into a single justified line and add to result
37+ result .append ("" .join (current_list ))
38+
39+ # Reset for next line
40+ current_list = []
41+ num_of_letters = 0
42+
43+ # Add current word to the line being built
44+ current_list .append (word )
45+ num_of_letters += len (word )
46+
47+ # form last line by join with space and left justify to maxWidth using ljust (python method)
48+ # that means pad additional spaces to the right to make string length equal to maxWidth
49+ result .append (" " .join (current_list ).ljust (maxWidth ))
50+
51+ return result
0 commit comments