Fully justify text
A free hard coding practice problem. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.
- Difficulty
- Hard
- Type
- Function
- Languages
- JavaScript, TypeScript or Python
Problem
Lay out words (non-empty, each at most width characters) into lines of exactly width characters. Pack greedily: put as many words on a line as fit with at least one space between neighbours. Every line except the last is fully justified: extra spaces are spread over the gaps between words as evenly as possible, and when they don't divide evenly the LEFT gaps get one more than the right ones. The last line, and any line holding a single word, is left-justified (one space between words) and padded with spaces on the right. Return the lines; no words gives no lines.
Function signature
// JavaScript
function justify(words, width)
// TypeScript
function justify(words: any, width: any): any
// Python
def justify(words, width):Examples
justify(["This","is","an","example","of","text","justification."], 16)→["This is an","example of text","justification. "]justify(["What","must","be","acknowledgment","shall","be"], 16)→["What must be","acknowledgment ","shall be "]
How checking works
Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.