Given an array arr[] of size n, where arr[i] denotes the number of characters in one word. Let k be the limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly.
Assume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces include spaces put at the end of every line except the last one.
The task is to minimize the following total cost where total cost = Sum of cost of all lines, where the cost of the line is = (Number of extra spaces in the line)2.
Examples:
Input: arr[] = [3, 2, 2, 5], k = 6
Output: 10
Explanation: Given a line can have 6 characters,
Line number 1: From word no. 1 to 1
Line number 2: From word no. 2 to 3
Line number 3: From word no. 4 to 4
So total cost = (6-3)2 + (6-2-2-1)2 = 32+12 = 10. As in the first line word length = 3 thus extra spaces = 6 - 3 = 3 and in the second line there are two words of length 2 and there is already 1 space between the two words thus extra spaces = 6 - 2 -2 -1 = 1. As mentioned in the problem description there will be no extra spaces in the last line. Placing the first and second words in the first line and the third word on the second line would take a cost of 02 + 42 = 16 (zero spaces on the first line and 6-2 = 4 spaces on the second), which isn't the minimum possible cost.Input: arr[] = [3, 2, 2], k = 4
Output: 5
Explanation: Given a line can have 4 characters,
Line 1: From word no. 1 to 1
Line 2: From word no. 2 to 2
Line 3: From word no. 3 to 3
Same explaination as above total cost = (4 - 3)2 + (4 - 2)2 = 5.
Table of Content

Why Greedy fails?
Greedy algorithms fail in this problem because they focus on filling the current line with as many words as possible, without considering that the last line has no cost. This is a crucial point for finding the best solution.
For example, with words[] = [3, 2, 2, 5] and k = 6, a greedy approach would put word[0] and word[1] on the first line, leaving 1 extra space (since the total length of the words plus spaces equals 6). The second line would have only word[2], leaving 4 extra spaces. The last line would have word[3], which doesn’t contribute to the cost.
This greedy method gives a total cost of 1*1 + 4*4 = 17, which is incorrect. The optimal arrangement is placing word[0] on the first line, word[1] and word[2] on the second line, and word[3] on the last line. This would result in a total cost of 10(explained in the first example).
Using recursion
This approach is based on recursively trying to place words on each line while ensuring that the total length of words, including spaces between them, does not exceed the maximum line width k. For each possible line configuration, we calculate the extra spaces at the end of the line and recursively solve the problem for the remaining words. The final cost is the sum of the squared extra spaces for all lines, with the last line contributing no cost. By exploring all possible ways of arranging the words across lines, we minimize the total cost and return the optimal result.
The recurrence relation for the word wrapping problem can be stated as follows: calculateCost(curr) represents the minimum cost for wrapping words starting from index curr to the end of the array.
The recurrence is:
- calculateCost(curr) = min { [(k - tot)^2 + calculateCost(i + 1)] } for all values of i from curr to n-1, where the total number of characters in the line (including spaces between words) does not exceed the width limit k.
Where:
- tot is the total number of characters in the current line, including the sum of word lengths and the spaces between them.
- k is the maximum allowed line width.
- (k - tot)^2 is the cost, calculated as the square of the extra spaces on the current line (if it fits within the width limit).
Base Case:
calculateCost(curr) = 0 if curr >= n, meaning when all words have been placed, no further cost is incurred.
// C++ program to minimize the cost to
// wrap the words.
#include <bits/stdc++.h>
using namespace std;
int calculateCost(int curr, int n, vector<int> &arr, int k) {
// Base case: If current index is beyond or at the
// last word, no cost
if (curr >= n)
return 0;
// Keeps track of the current line's total character count
int sum = 0;
// Initialize with a large value to find the minimum cost
int ans = INT_MAX;
// Try placing words from the current position to the next
for (int i = curr; i < n; i++) {
// Add the length of the current word
sum += arr[i];
// Including spaces between words
int tot = sum + (i - curr);
// If the total exceeds the line width,
// break out of the loop
if (tot > k)
break;
// If this is not the last word in the array, compute the
// cost for the next line
if (i != n - 1) {
int temp = (k - tot) * (k - tot) +
calculateCost(i + 1, n, arr, k);
ans = min(ans, temp);
}
else {
// If it's the last word, there's no cost added
ans = 0;
}
}
return ans;
}
int solveWordWrap(vector<int> &arr, int k) {
int n = arr.size();
return calculateCost(0, n, arr, k);
}
int main() {
int k = 6;
vector<int> arr = {3, 2, 2, 5};
int res = solveWordWrap(arr, k);
cout << res << endl;
return 0;
}
// Java program to minimize the cost to
// wrap the words.
import java.util.*;
class GfG {
static int calculateCost(int curr, int n, int[] arr,
int k) {
// Base case: If current index is beyond or at the
// last word, no cost
if (curr >= n)
return 0;
// Keeps track of the current line's total character
// count
int sum = 0;
// Initialize with a large value to find the minimum
// cost
int ans = Integer.MAX_VALUE;
// Try placing words from the current position to
// the next
for (int i = curr; i < n; i++) {
// Add the length of the current word
sum += arr[i];
// Including spaces between words
int tot = sum + (i - curr);
// If the total exceeds the line width, break
// out of the loop
if (tot > k)
break;
// If this is not the last word in the array,
// compute the cost for the next line
if (i != n - 1) {
int temp
= (k - tot) * (k - tot)
+ calculateCost(i + 1, n, arr, k);
ans = Math.min(ans, temp);
}
else {
// If it's the last word, there's no cost added
ans = 0;
}
}
return ans;
}
static int solveWordWrap(int[] arr, int k) {
int n = arr.length;
return calculateCost(0, n, arr, k);
}
public static void main(String[] args) {
int[] arr = { 3, 2, 2, 5 };
int k = 6;
int res = solveWordWrap(arr, k);
System.out.println(res);
}
}
# Python program to minimize the cost to wrap the words.
import sys
def calculateCost(curr, n, arr, k):
# Base case: If current index is beyond or at the last
# word, no cost
if curr >= n:
return 0
# Keeps track of the current line's total character count
sum = 0
# Initialize with a large value to find the minimum cost
ans = sys.maxsize
# Try placing words from the current position to the next
for i in range(curr, n):
# Add the length of the current word
sum += arr[i]
# Including spaces between words
tot = sum + (i - curr)
# If the total exceeds the line width, break out of the
# loop
if tot > k:
break
# If this is not the last word in the array, compute the
# cost for the next line
if i != n - 1:
temp = (k - tot) * (k - tot) + calculateCost(i + 1, n, arr, k)
ans = min(ans, temp)
# If it's the last word, there's no cost added
else:
ans = 0
return ans
def solveWordWrap(arr, k):
n = len(arr)
return calculateCost(0, n, arr, k)
if __name__ == "__main__":
arr = [3, 2, 2, 5]
k = 6
res = solveWordWrap(arr, k)
print(res)
// C# program to minimize the cost to
// wrap the words.
using System;
class GfG {
static int calculateCost(int curr, int n, int[] arr,
int k) {
// Base case: If current index is beyond or at the
// last word, no cost
if (curr >= n)
return 0;
// Keeps track of the current line's total character
// count
int sum = 0;
// Initialize with a large value to find the minimum
// cost
int ans = int.MaxValue;
// Try placing words from the current position to
// the next
for (int i = curr; i < n; i++) {
// Add the length of the current word
sum += arr[i];
// Including spaces between words
int tot = sum + (i - curr);
// If the total exceeds the line width, break
// out of the loop
if (tot > k)
break;
// If this is not the last word in the array,
// compute the cost for the next line
if (i != n - 1) {
int temp
= (k - tot) * (k - tot)
+ calculateCost(i + 1, n, arr, k);
ans = Math.Min(ans, temp);
}
else {
// If it's the last word, there's no cost added
ans = 0;
}
}
return ans;
}
static int solveWordWrap(int[] arr, int k) {
int n = arr.Length;
return calculateCost(0, n, arr, k);
}
public static void Main(string[] args) {
int[] arr = { 3, 2, 2, 5 };
int k = 6;
int res = solveWordWrap(arr, k);
Console.WriteLine(res);
}
}
// JavaScript program to minimize the cost to wrap the
// words.
function calculateCost(curr, n, arr, k) {
// Base case: If current index is beyond or at the last
// word, no cost
if (curr >= n) {
return 0;
}
// Keeps track of the current line's total character
// count
let sum = 0;
// Initialize with a large value to find the minimum
// cost
let ans = Infinity;
// Try placing words from the current position to the
// next
for (let i = curr; i < n; i++) {
// Add the length of the current word
sum += arr[i];
// Including spaces between words
let tot = sum + (i - curr);
// If the total exceeds the line width, break out of
// the loop
if (tot > k) {
break;
}
// If this is not the last word in the array,
// compute the cost for the next line
if (i !== n - 1) {
let temp = (k - tot) * (k - tot)
+ calculateCost(i + 1, n, arr, k);
ans = Math.min(ans, temp);
}
else {
// If it's the last word, there's no cost added
ans = 0;
}
}
return ans;
}
function solveWordWrap(arr, k) {
let n = arr.length;
return calculateCost(0, n, arr, k);
}
const arr = [ 3, 2, 2, 5 ];
const k = 6;
const res = solveWordWrap(arr, k);
console.log(res);
Output
10
The above approach will have a exponential time complexity.
Using Top-Down DP (Memoization) - O(n^2) Time and O(n) Space
If we observe closely, the recursive function calculateCost() in the word wrap problem also follows the overlapping subproblems property, meaning that the same subproblems are being solved repeatedly in different recursive calls. We can optimize this using memoization. Since the only changing parameter in the recursive calls is curr, which ranges from 0 to n-1 (where n is the number of words), we can use a 1D array of size n to store the results of previously computed subproblems. By initializing this array with -1 to indicate that a subproblem hasn't been computed yet, we can avoid redundant calculations and improve efficiency.
// C++ program to minimize the cost to
// wrap the words.
#include <bits/stdc++.h>
using namespace std;
int calculateCost(int curr, int n, vector<int> &arr,
int k, vector<int> &memo) {
// Base case: If current index is beyond or at
// the last word, no cost
if (curr >= n)
return 0;
if (memo[curr] != -1)
return memo[curr];
// Keeps track of the current line's total character
// count
int sum = 0;
// Initialize with a large value to find the minimum cost
int ans = INT_MAX;
// Try placing words from the current position to the next
for (int i = curr; i < n; i++) {
// Add the length of the current word
sum += arr[i];
// Including spaces between words
int tot = sum + (i - curr);
// If the total exceeds the line width,
// break out of the loop
if (tot > k)
break;
// If this is not the last word in the array, compute
// the cost for the next line
if (i != n - 1) {
int temp = (k - tot) * (k - tot) +
calculateCost(i + 1, n, arr, k, memo);
ans = min(ans, temp);
}
else {
// If it's the last word, there's no cost added
ans = 0;
}
}
return memo[curr] = ans;
}
int solveWordWrap(vector<int> &arr, int k) {
int n = arr.size();
vector<int> memo(n, -1);
return calculateCost(0, n, arr, k, memo);
}
int main() {
int k = 6;
vector<int> arr = {3, 2, 2, 5};
int res = solveWordWrap(arr, k);
cout << res << endl;
return 0;
}
// Java program to minimize the cost to
// wrap the words.
import java.util.*;
class GfG {
static int calculateCost(int curr, int n, int[] arr,
int k, int[] memo) {
// Base case: If current index is beyond or at the
// last word, no cost
if (curr >= n) {
return 0;
}
// If the value is already computed, return the
// memoized result
if (memo[curr] != -1) {
return memo[curr];
}
// Keeps track of the current line's total character
// count
int sum = 0;
// Initialize with a large value to find the minimum
// cost
int ans = Integer.MAX_VALUE;
// Try placing words from the current position to
// the next
for (int i = curr; i < n; i++) {
// Add the length of the current word
sum += arr[i];
// Including spaces between words
int tot = sum + (i - curr);
// If the total exceeds the line width, break
// out of the loop
if (tot > k) {
break;
}
// If this is not the last word in the array,
// compute the cost for the next line
if (i != n - 1) {
int temp = (k - tot) * (k - tot)
+ calculateCost(i + 1, n, arr, k,
memo);
ans = Math.min(ans, temp);
}
else {
// If it's the last word, there's no cost added
ans = 0;
}
}
memo[curr] = ans;
return ans;
}
static int solveWordWrap(int[] arr, int k) {
int n = arr.length;
int[] memo = new int[n];
Arrays.fill(memo,
-1);
return calculateCost(0, n, arr, k, memo);
}
public static void main(String[] args) {
int k = 6;
int[] arr = { 3, 2, 2, 5 };
int res = solveWordWrap(arr, k);
System.out.println(res);
}
}
# Python program to minimize the cost to wrap the words.
def calculateCost(curr, n, arr, k, memo):
# Base case: If current index is beyond or at the
# last word, no cost
if curr >= n:
return 0
# If the value is already computed, return the
# memoized result
if memo[curr] != -1:
return memo[curr]
# Keeps track of the current line's total
# character count
sumChars = 0
# Initialize with a large value to find the minimum cost
ans = float('inf')
# Try placing words from the current position to the next
for i in range(curr, n):
# Add the length of the current word
sumChars += arr[i]
# Including spaces between words
total = sumChars + (i - curr)
# If the total exceeds the line width,
# break out of the loop
if total > k:
break
# If this is not the last word in the array, compute
# the cost for the next line
if i != n - 1:
temp = (k - total) * (k - total) + \
calculateCost(i + 1, n, arr, k, memo)
ans = min(ans, temp)
# If it's the last word, there's no cost added
else:
ans = 0
# Memoize the result before returning
memo[curr] = ans
return ans
def solveWordWrap(arr, k):
n = len(arr)
memo = [-1] * n
return calculateCost(0, n, arr, k, memo)
if __name__ == "__main__":
k = 6
arr = [3, 2, 2, 5]
print(solveWordWrap(arr, k))
// C# program to minimize the cost to wrap the words.
using System;
using System.Collections.Generic;
class GfG {
static int calculateCost(int curr, int n, List<int> arr,
int k, int[] memo) {
// Base case: If current index is beyond or at the
// last word, no cost
if (curr >= n)
return 0;
// If the value is already computed, return the
// memoized result
if (memo[curr] != -1)
return memo[curr];
// Keeps track of the current line's total character
// count
int sumChars = 0;
// Initialize with a large value to find the minimum
// cost
int ans = int.MaxValue;
// Try placing words from the current position to
// the next
for (int i = curr; i < n; i++) {
// Add the length of the current word
sumChars += arr[i];
// Including spaces between words
int total = sumChars + (i - curr);
// If the total exceeds the line width, break
// out of the loop
if (total > k)
break;
// If this is not the last word in the array,
// compute the cost for the next line
if (i != n - 1) {
int temp = (k - total) * (k - total)
+ calculateCost(i + 1, n, arr, k,
memo);
ans = Math.Min(ans, temp);
}
else {
// If it's the last word, there's no cost added
ans = 0;
}
}
// Memoize the result before returning
memo[curr] = ans;
return ans;
}
static int solveWordWrap(List<int> arr, int k) {
int n = arr.Count;
int[] memo = new int[n];
for (int i = 0; i < n; i++)
memo[i] = -1;
return calculateCost(0, n, arr, k, memo);
}
static void Main() {
int k = 6;
List<int> arr = new List<int> { 3, 2, 2, 5 };
int res = solveWordWrap(arr, k);
Console.WriteLine(res);
}
}
// JavaScript program to minimize the cost to wrap the words.
function calculateCost(curr, n, arr, k, memo) {
// Base case: If current index is beyond or at the last
// word, no cost
if (curr >= n) {
return 0;
}
// If the value is already computed, return the memoized
// result
if (memo[curr] !== -1) {
return memo[curr];
}
// Keeps track of the current line's total character
// count
let sumChars = 0;
// Initialize with a large value to find the minimum
// cost
let ans = Number.MAX_VALUE;
// Try placing words from the current position to the
// next
for (let i = curr; i < n; i++) {
// Add the length of the current word
sumChars += arr[i];
// Including spaces between words
let total = sumChars + (i - curr);
// If the total exceeds the line width, break out of
// the loop
if (total > k) {
break;
}
// If this is not the last word in the array,
// compute the cost for the next line
if (i !== n - 1) {
let temp
= (k - total) * (k - total)
+ calculateCost(i + 1, n, arr, k, memo);
ans = Math.min(ans, temp);
}
// If it's the last word, there's no cost added
else {
ans = 0;
}
}
// Memoize the result before returning
memo[curr] = ans;
return ans;
}
function solveWordWrap(arr, k) {
const n = arr.length;
const memo = new Array(n).fill(
-1);
return calculateCost(0, n, arr, k, memo);
}
const k = 6;
const arr = [ 3, 2, 2, 5 ];
const res = solveWordWrap(arr, k);
console.log(res);
Output
10
Using Bottom-Up DP (Tabulation) - O(n*n) Time and O(n) Space
The approach is similar to the previous one. Just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner.
Refer to Word Wrap problem (Tabulation Approach) for explanation and code.