Fully Justify Paragraph Text to a Fixed Column Width

Last updated: November 29, 2026

Quick Overview

Given a list of words and a maximum line width, lay the text out greedily so each line has as many words as fit, then pad lines with spaces so each is exactly the width: extra spaces are spread as evenly as possible with leftmost gaps getting more, and the last line and single-word lines are left-aligned.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given a list of words and a maximum line width, lay the text out greedily so each line has as many words as fit, then pad lines with spaces so each is exactly the width: extra spaces are spread as evenly as possible with leftmost gaps getting more, and the last line and single-word lines are left-aligned.

Text layout is core to Google Docs and printing, and this onsite question is mostly about precise implementation of a spec. The interviewer looks for a clean greedy line-breaking pass, exact space distribution with divmod, and correct handling of the last line and single-word lines.

What the Interviewer Expects
  • Uses greedy line filling with the single-space minimum in the length check
  • Distributes extra spaces with divmod, giving leftover spaces to the leftmost gaps
  • Left-aligns the last line and lines with a single word
  • Pads every line to exactly the width
  • Handles words longer than the width explicitly
Key Topics to Cover
Greedy Algorithms
String Formatting
Text Layout
Simulation
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Greedy breaking can leave ugly ragged lines; how does minimum-raggedness (Knuth-Plass style DP) work?
  • Support hyphenation of long words.
  • Words have variable pixel widths in a proportional font; what changes?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: words (non-empty strings without spaces) and width.
  • Each line takes as many words as fit with single spaces between them.
  • Non-last lines with two or more words: distribute spaces so t...
High-Level Design

Two nested steps per line. First, starting from word i, extend j while current_length + 1 + len(words[j]) <= width; the +1 reserves at least one space per gap. Second, format the line. For a n...


Submit Your Answer
Markdown supported