This reads like a simple string formatting task, but the bookkeeping is what makes it hard. There are three separate decisions: which words go on each line, how many spaces go between those words, and which lines follow a different rule.
The spacing is the part that takes care. When the extra spaces on a line do not divide evenly among the gaps between words, the leftmost gaps each get one extra space. Two lines also ignore even distribution entirely: a line holding a single word is left-justified and padded on the right, and the last line is always left-justified no matter how many words it holds.
Underneath, this is a greedy packing problem. Pack as many words as fit on a line, then format that line according to the justification rules.
1 <= words.length <= 300 → A line scan that visits each word once is more than fast enough; no asymptotic concern drives the design here.1 <= words[i].length <= 20 → Every word fits within maxWidth, so no word ever needs to be split across lines.1 <= maxWidth <= 100 → Lines are short, so string building per line is cheap.There is no brute-force-to-optimal progression here. The problem fixes a single strategy: pack words into lines greedily, then format each line. The difficulty is in the formatting, not in choosing an algorithm.
Fill a line one word at a time. Keep adding words while the running total (the words plus one space between each adjacent pair) stays within maxWidth. When the next word would push the line over, the current line is complete. Distribute its spaces, then start the next line at the word that did not fit.
Formatting a finished line splits into three cases:
The greedy packing is forced by the problem, which requires as many words per line as will fit. Leaving room on a line never helps, because the rules judge each line on its own, not on the raggedness of the paragraph (which is what would call for dynamic programming). Once the words on a line are fixed, the spacing is determined: with g gaps and s total spaces, each gap gets s / g spaces and the first s % g gaps take one more. That places (s % g) extra spaces, so the widths sum back to s and the leftmost gaps stay widest, exactly as the rules require.
i = 0 to track the current word.i < words.length:words[i] and keep adding words as long as the total length (words + minimum one space between each) does not exceed maxWidth.Loading animation...