# Text Justification LeetCode Solution

Here, We see Text Justification problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

## Problem Statement ->

Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

Note:

• A word is defined as a character sequence consisting of non-space characters only.
• Each word’s length is guaranteed to be greater than `0` and not exceed maxWidth.
• The input array `words` contains at least one word.
```Example 1:
Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
Output:
[
"This    is    an",
"example  of text",
"justification.  "
]```
```Example 2:
Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
Output:
[
"What   must   be",
"acknowledgment  ",
"shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.

Example 3:
Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
Output:
[
"Science  is  what we",
"understand      well",
"enough to explain to",
"a  computer.  Art is",
"everything  else  we",
"do                  "
]```

## Text Justification Leetcode Solution C++ ->

```.wp-block-code {
border: 0;
}

.wp-block-code > div {
overflow: auto;
}

.shcb-language {
border: 0;
clip: rect(1px, 1px, 1px, 1px);
-webkit-clip-path: inset(50%);
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
width: 1px;
word-wrap: normal;
word-break: normal;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string>res;
if(maxWidth == 0) return {""};
int i = 0, j = 0;
while(j != words.size()){
int len = -1;
while(j < words.size() && len + words[j].size() + 1 <= maxWidth)
len += words[j++].size() + 1;
int space = maxWidth - len + j - i - 1;
int k = i;
while(space){
words[k++] += " ";
space--;
if(j != words.size() && (k == j - 1 || k == j)) k = i;
if(j == words.size() && k == j) k = j - 1;
}
string line = "";
for(int l = i; l < j; l++)
line += words[l];
res.push_back(line);
i = j;
}
return res;
}
};
```Code language: C++ (cpp)```

## Text Justification Leetcode Solution Java ->

``````class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> lines = new ArrayList<String>();

int index = 0;
while (index < words.length) {
int count = words[index].length();
int last = index + 1;
while (last < words.length) {
if (words[last].length() + count + 1 > maxWidth) break;
count += words[last].length() + 1;
last++;
}

StringBuilder builder = new StringBuilder();
int diff = last - index - 1;
if (last == words.length || diff == 0) {
for (int i = index; i < last; i++) {
builder.append(words[i] + " ");
}
builder.deleteCharAt(builder.length() - 1);
for (int i = builder.length(); i < maxWidth; i++) {
builder.append(" ");
}
} else {
int spaces = (maxWidth - count) / diff;
int r = (maxWidth - count) % diff;
for (int i = index; i < last; i++) {
builder.append(words[i]);
if (i < last - 1) {
for (int j = 0; j <= (spaces + ((i - index) < r ? 1 : 0)); j++) {
builder.append(" ");
}
}
}
}
index = last;
}
return lines;
}
}
```Code language: Java (java)```

## Text Justification Leetcode Solution JavaScript ->

``````var fullJustify = function(words, maxWidth) {
const res = [];
let buf = [];
let width = maxWidth;

words.forEach(word => {
if (word.length <= (width - buf.length)) {
buf.push(word);
width -= word.length;
} else {
buf = [word];
width = maxWidth - word.length;
}
});

if (buf.length) {
let str = buf.join(' ');
str += ' '.repeat(maxWidth - str.length);
res.push(str);
}

return res;
};

let spaces = maxWidth - buf.reduce((acc, cur) => cur.length + acc, 0);
if (buf.length === 1) {
buf += ' '.repeat(spaces);
res.push(buf);
return;
}

spaces -= buf.length - 1;

const end = buf.length - 1;
let index = 0;

while (spaces-- > 0) {
buf[index] += ' ';

index = (index + 1) % end;
}

res.push(buf.join(' '))
};
```Code language: JavaScript (javascript)```

## Text Justification Leetcode Solution Python ->

``````class Solution(object):
def fullJustify(self, words, maxWidth):
i, N, result = 0, len(words), []
while i < N:
oneLine, j, currWidth, positionNum, spaceNum = [words[i]], i + 1, len(words[i]), 0,maxWidth - len(words[i])
while j < N and currWidth + 1 + len(words[j]) <= maxWidth:
oneLine.append(words[j])
currWidth += 1 + len(words[j])
spaceNum -= len(words[j])
positionNum, j = positionNum + 1, j + 1
i = j
if i < N and positionNum:
spaces = [' ' * (spaceNum / positionNum + (k < spaceNum % positionNum)) for k in range(positionNum)] + ['']
else:
spaces = [' '] * positionNum + [' ' * (maxWidth - currWidth)]
result.append(''.join([s for pair in zip(oneLine, spaces) for s in pair]))
return result
```Code language: Python (python)```

#### Contains Duplicate II LeetCode Solution

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such…

#### Convert Sorted List to Binary Search Tree LeetCode Solution

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a …

#### 3Sum LeetCode Solution

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i !=…

#### Word Search II LeetCode Solution

Given an m x n board of characters and a list of strings words, return all words on the board.

#### Remove Element LeetCode Solution

Given an integer array nums and an integer val, remove all occurrences of val in…