Format Words into Fixed-Width Lines
Company: eBay
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in string manipulation, greedy line-packing algorithms, and attention to implementation details such as spacing distribution and edge-case handling.
Constraints
- 1 <= len(words) <= 300
- 1 <= len(words[i]) <= 20
- words[i] contains no spaces
- 1 <= maxWidth <= 100
- Every word length is at most maxWidth
Examples
Input: (["This", "is", "an", "example", "of", "word", "formatting"], 16)
Expected Output: ["This is an", "example of word", "formatting "]
Explanation: The first two lines are fully justified, and the last line is left-aligned and padded on the right.
Input: (["What", "must", "be", "acknowledgment", "shall", "be"], 16)
Expected Output: ["What must be", "acknowledgment ", "shall be "]
Explanation: The second line contains only one word, so it is left-aligned with trailing spaces.
Input: (["Science", "is", "what", "we", "understand", "well"], 20)
Expected Output: ["Science is what we", "understand well "]
Explanation: The first line needs 5 spaces across 3 gaps, so the leftmost two gaps get 2 spaces and the last gap gets 1.
Input: (["Hello"], 10)
Expected Output: ["Hello "]
Explanation: A single last-line word is left-aligned and padded with spaces to width 10.
Input: (["a", "b", "c"], 1)
Expected Output: ["a", "b", "c"]
Explanation: With maxWidth = 1, each line can contain only one character, so each word forms its own line.
Hints
- First decide which words belong to the current line using a greedy scan, then format that line.
- For a non-last line with k gaps and s spaces to place, each gap gets s // k spaces, and the first s % k gaps get one extra space.