ExamAdda Logo

Text Justification

Easy

Given an array of strings words and an integer maxWidth, format the text such that each line has exactly maxWidth characters and is fully justified.

You should pack words in a greedy manner, placing as many words as possible on each line.

Extra spaces should be distributed as evenly as possible between words.

If the number of spaces cannot be evenly distributed, the leftmost gaps should receive more spaces than the rightmost gaps.

The last line of text should be left-justified, and no extra spaces should be inserted between words except the single spaces required.

Example 1

Input

7
This
is
an
example
of
text
justification.
16

Output

This    is    an
example  of text
justification.

Explanation

The words are packed greedily into each line.

Extra spaces are distributed evenly between words, and the last line is left-justified.

Example 2

Input

6
What
must
be
acknowledgment
shall
be
16

Output

What   must   be
acknowledgment
shall be

Explanation

The first line is fully justified.

The second line contains a single word.

The last line is left-justified.

Constraints

1 ≤ words.length ≤ 300
1 ≤ words[i].length ≤ 20
words[i] consists of English letters and symbols.
1 ≤ maxWidth ≤ 100
The length of each word is less than or equal to maxWidth.

Hints:

Hint 1

Greedily place as many words as possible in the current line without exceeding maxWidth.

Hint 2

For non-last lines, distribute spaces evenly across the gaps. If extra spaces remain, assign them to the leftmost gaps. The last line should be left-justified.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 4, 2026

Last updated

Aug 5, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output