Fully Justify Post Text Into Fixed-Width Display Lines
Last updated: November 29, 2026
Quick Overview
Given the words of a post and a line width W, lay the words out greedily into lines of exactly W characters, distributing extra spaces as evenly as possible with leftover spaces going to the leftmost gaps, and left-justify the last line and single-word lines.
Meta
November 29, 20260
0
0 solved
Given the words of a post and a line width W, lay the words out greedily into lines of exactly W characters, distributing extra spaces as evenly as possible with leftover spaces going to the leftmost gaps, and left-justify the last line and single-word lines.
Text layout is a real concern for feed rendering on fixed-width surfaces like Portal and wearable displays, and this classic is a test of disciplined implementation rather than clever insight. Meta interviewers watch for clean helper boundaries and correct handling of every special line.
What the Interviewer Expects
- Pack words greedily, counting the mandatory single spaces
- Distribute extra spaces with divmod across gaps
- Give leftover spaces to the leftmost gaps
- Left-justify the last line and pad with trailing spaces
- Handle single-word lines
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 globally instead of greedily (Knuth-Plass)?
- How would you hyphenate long words?
- How would this change with variable-width fonts?
- How would you handle words longer than W?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Each word has length at most
Wand contains no spaces. - Every output line has exactly
Wcharacters. - Middle lines are fully justified; the last line and any line with one word are left-justifi...
High-Level Design
Walk the words, building a line while line_len + len(word) + count_of_words_in_line <= W (the count term is the minimum single spaces needed). When the next word does not fit, emit the line.
To jus...