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
Coding & Algorithms
Frontend Engineer
Meta
November 29, 2026
Frontend Engineer
Onsite
Coding & Algorithms
Hard

0

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
string formatting
greedy
simulation
text layout
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
  • 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 Problems
Sample Answer
Requirements
  • Each word has length at most W and contains no spaces.
  • Every output line has exactly W characters.
  • 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...


Submit Your Answer
Markdown supported