As reported: Atlassian Karat screen (2025), second of two medium coding problems: a list of sentences (words separated by spaces) and an exact length; regroup the words, keeping their order, into lines of exactly that length, padding with
-spread evenly from left to right; the last line is not padded, and a line with a single word is not padded. Also asked at Atlassian in a 2025 P40 Karat screen as a problem similar to LeetCode 68 (Text Justification), with one follow-up.
Given lines (sentences whose words are separated by spaces) and width, take all words in order and:
- Pack them greedily: each output line takes as many of the next words as fit when joined by single
-characters withinwidth. - Pad every line except the last to exactly
widthcharacters by adding more-between its words. Spread the dashes as evenly as possible; when they do not divide evenly, the leftmost gaps get one more. - The last line, and any line holding a single word, stay as they are (words joined by single
-, no padding).
Example 1
lines = ["The day began as still as the","night abruptly lighted with","brilliant flame"], width = 24
Output: ["The--day--began-as-still",
"as--the--night--abruptly",
"lighted--with--brilliant",
"flame"]
Example 2
same lines, width = 25
Output: ["The-day-began-as-still-as",
"the-----night----abruptly",
"lighted---with--brilliant",
"flame"]
Constraints: 1 ≤ total words ≤ 5000; every word has 1 … width letters; 1 ≤ width ≤ 100; words are separated by single spaces.
Code runner format: one JSON value per line: lines, then width. Implement justifyLines(lines, width); the harness prints the lines.