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.
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++
// 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
// 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
# 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#
// 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
// 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);
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++
// 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
// 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
# 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#
// 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
// 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);
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem