Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
Note:
0 and not exceed maxWidth.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 " ]
Constraints:
1 <= words.length <= 3001 <= words[i].length <= 20words[i] consists of only English letters and symbols.1 <= maxWidth <= 100words[i].length <= maxWidthProblem summary: 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. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
["This", "is", "an", "example", "of", "text", "justification."] 16
["What","must","be","acknowledgment","shall","be"] 16
["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"] 20
rearrange-spaces-between-words)divide-a-string-into-groups-of-size-k)split-message-based-on-limit)import java.util.*;
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> ans = new ArrayList<>();
int i = 0;
while (i < words.length) {
int j = i + 1;
int lineChars = words[i].length();
// Greedily pack as many words as possible into the line.
while (j < words.length && lineChars + 1 + words[j].length() <= maxWidth) {
lineChars += 1 + words[j].length();
j++;
}
int wordCount = j - i;
StringBuilder line = new StringBuilder();
if (j == words.length || wordCount == 1) {
// Last line (or single-word line): left-justified.
for (int k = i; k < j; k++) {
if (k > i) line.append(' ');
line.append(words[k]);
}
while (line.length() < maxWidth) line.append(' ');
} else {
int totalWordChars = 0;
for (int k = i; k < j; k++) totalWordChars += words[k].length();
int spaces = maxWidth - totalWordChars;
int gaps = wordCount - 1;
int even = spaces / gaps;
int extra = spaces % gaps;
for (int k = i; k < j - 1; k++) {
line.append(words[k]);
int count = even + ((k - i) < extra ? 1 : 0);
for (int s = 0; s < count; s++) line.append(' ');
}
line.append(words[j - 1]);
}
ans.add(line.toString());
i = j;
}
return ans;
}
}
import "strings"
func fullJustify(words []string, maxWidth int) []string {
ans := []string{}
i := 0
for i < len(words) {
j := i + 1
lineChars := len(words[i])
for j < len(words) && lineChars+1+len(words[j]) <= maxWidth {
lineChars += 1 + len(words[j])
j++
}
wordCount := j - i
var line strings.Builder
if j == len(words) || wordCount == 1 {
for k := i; k < j; k++ {
if k > i {
line.WriteByte(' ')
}
line.WriteString(words[k])
}
for line.Len() < maxWidth {
line.WriteByte(' ')
}
} else {
totalWordChars := 0
for k := i; k < j; k++ {
totalWordChars += len(words[k])
}
spaces := maxWidth - totalWordChars
gaps := wordCount - 1
even := spaces / gaps
extra := spaces % gaps
for k := i; k < j-1; k++ {
line.WriteString(words[k])
count := even
if (k - i) < extra {
count++
}
line.WriteString(strings.Repeat(" ", count))
}
line.WriteString(words[j-1])
}
ans = append(ans, line.String())
i = j
}
return ans
}
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
ans: List[str] = []
i = 0
while i < len(words):
j = i + 1
line_chars = len(words[i])
while j < len(words) and line_chars + 1 + len(words[j]) <= maxWidth:
line_chars += 1 + len(words[j])
j += 1
line_words = words[i:j]
word_count = len(line_words)
if j == len(words) or word_count == 1:
line = ' '.join(line_words)
line += ' ' * (maxWidth - len(line))
else:
total_word_chars = sum(len(w) for w in line_words)
spaces = maxWidth - total_word_chars
gaps = word_count - 1
even, extra = divmod(spaces, gaps)
parts = []
for idx, w in enumerate(line_words[:-1]):
parts.append(w)
parts.append(' ' * (even + (1 if idx < extra else 0)))
parts.append(line_words[-1])
line = ''.join(parts)
ans.append(line)
i = j
return ans
impl Solution {
pub fn full_justify(words: Vec<String>, max_width: i32) -> Vec<String> {
let max_width = max_width as usize;
let mut ans = Vec::new();
let mut i = 0usize;
while i < words.len() {
let mut j = i + 1;
let mut line_chars = words[i].len();
while j < words.len() && line_chars + 1 + words[j].len() <= max_width {
line_chars += 1 + words[j].len();
j += 1;
}
let word_count = j - i;
let mut line = String::new();
if j == words.len() || word_count == 1 {
for k in i..j {
if k > i {
line.push(' ');
}
line.push_str(&words[k]);
}
line.push_str(&" ".repeat(max_width - line.len()));
} else {
let mut total_word_chars = 0usize;
for k in i..j {
total_word_chars += words[k].len();
}
let spaces = max_width - total_word_chars;
let gaps = word_count - 1;
let even = spaces / gaps;
let extra = spaces % gaps;
for k in i..j - 1 {
line.push_str(&words[k]);
let count = even + if (k - i) < extra { 1 } else { 0 };
line.push_str(&" ".repeat(count));
}
line.push_str(&words[j - 1]);
}
ans.push(line);
i = j;
}
ans
}
}
function fullJustify(words: string[], maxWidth: number): string[] {
const ans: string[] = [];
let i = 0;
while (i < words.length) {
let j = i + 1;
let lineChars = words[i].length;
while (j < words.length && lineChars + 1 + words[j].length <= maxWidth) {
lineChars += 1 + words[j].length;
j++;
}
const wordCount = j - i;
let line = '';
if (j === words.length || wordCount === 1) {
line = words.slice(i, j).join(' ');
line += ' '.repeat(maxWidth - line.length);
} else {
let totalWordChars = 0;
for (let k = i; k < j; k++) totalWordChars += words[k].length;
const spaces = maxWidth - totalWordChars;
const gaps = wordCount - 1;
const even = Math.floor(spaces / gaps);
const extra = spaces % gaps;
for (let k = i; k < j - 1; k++) {
line += words[k];
line += ' '.repeat(even + (k - i < extra ? 1 : 0));
}
line += words[j - 1];
}
ans.push(line);
i = j;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.