Tutorialspoint
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)
StringsTCS (Tata Consultancy Services)Walmart
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Iterate through words and group them that can fit in one line based on maxWidth.
 Step 2: For each line, calculate the total number of spaces needed for justification.
 Step 3: Determine if it's the last line or contains only one word (left-justify only).
 Step 4: For full justification, distribute spaces evenly between words.
 Step 5: Handle extra spaces by distributing them from left to right.
 Step 6: Build the justified line string and add to result array.
 Step 7: Continue until all words are processed.

Submitted Code :