Fully Justify Paragraph Lines for a Word Layout Engine
Last updated: November 29, 2026
Quick Overview
Given a list of words and a line width, greedily pack words into lines and pad each line with spaces so it is exactly the width, distributing extra spaces left first, with the last line and single-word lines left aligned.
Microsoft
November 29, 20260
0
0 solved
Given a list of words and a line width, greedily pack words into lines and pad each line with spaces so it is exactly the width, distributing extra spaces left first, with the last line and single-word lines left aligned.
An onsite question in the style of Microsoft Office teams, where text layout in Word or Outlook is core product code. The interviewer cares less about the algorithm, which is greedy, and more about clean index arithmetic and getting every special case right on the first pass.
What the Interviewer Expects
- Greedy line packing with a running length that includes one space per gap
- Even distribution with remainder spaces assigned to the leftmost gaps
- Left-justify the last line and any one-word line
- Pad every line to exactly the width
- Walk through a full example before running
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you minimize raggedness across the paragraph instead of packing greedily?
- How would variable-width fonts change the approach?
- How would you handle a word longer than the line width?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Every word fits within the width. Pack as many words per line as possible with at least one space between them. For a full line that is not the last, spread the leftover spaces across gaps as evenly a...
High-Level Design
Two phases per line. Packing: starting at word i, extend j while the letters so far plus the new word plus one space per gap still fit; the gap count is j - i. Spacing: with gaps = j - i - 1, ...