
Problem
Solution
Submissions
Text Justification
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to format text such that each line has exactly maxWidth characters and is fully justified (left and right aligned). You should pack words in a greedy approach; that is, pack as many words as you can in each line. Add extra spaces when necessary so that each line has exactly maxWidth characters.
Example 1
- Input: words = ["This", "is", "an", "example"], maxWidth = 16
- Output: ["This is an", "example "]
- Explanation:
- Step 1: First line: "This", "is", "an" can fit with total 11 characters including spaces.
- Step 2: Add extra spaces evenly: "This is an" (16 characters).
- Step 3: Second line: "example" with padding: "example " (16 characters).
Example 2
- Input: words = ["What", "must", "be"], maxWidth = 12
- Output: ["What must be"]
- Explanation:
- Step 1: All words fit in one line with total 10 characters including normal spaces.
- Step 2: Since it's the last line, left-justify: "What must be" (12 characters).
Constraints
- 1 ≤ words.length ≤ 300
- 1 ≤ words[i].length ≤ 20
- 1 ≤ maxWidth ≤ 100
- words[i] consists of only English letters and symbols
- Time Complexity: O(n * maxWidth)
- Space Complexity: O(maxWidth)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Group words that can fit in one line based on maxWidth.
- For each line, calculate total spaces needed for justification.
- Distribute extra spaces evenly between words.
- Handle the last line separately (left-justify only).
- If only one word in a line, left-justify with trailing spaces.
- Use string manipulation to build each justified line.