Word Wrap | Practice | GeeksforGeeks

Given an array nums[] of size n, where nums[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. 
You have to minimize the following total cost where total cost = Sum of cost of all lines, where cost of line is = (Number of extra spaces in the line)2.
Example 1:
Input: nums = {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 word of length 2 and there already
1 space between two word 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 first and second word
in first line and third word on second line
would take a cost of 02 + 42 = 16 (zero spaces
on first line and 6-2 = 4 spaces on second),
which isn't the minimum possible cost.

Example 2:
Input: nums = {3,2,2}, k = 4
Output: 5
Explanation: Given a line can have 4 
characters,
Line number 1: From word no. 1 to 1
Line number 2: From word no. 2 to 2
Line number 3: From word no. 3 to 3
Same explaination as above total cost
= (4 - 3)2 + (4 - 2)2 = 5.


Your Task:
You don't need to read or print anyhting. Your task is to complete the function solveWordWrap() which takes nums and k as input paramater and returns the minimized total cost.
 
Expected Time Complexity: O(n2)
Expected Space Complexity: O(n)
 
Constraints:
1 ≤ n ≤ 500
1 ≤ nums[i] ≤ 1000
max(nums[i]) ≤ k ≤ 2000
+1
jindalpraval7912 days ago
int dp[505][2005];
    int solve(int index, int remaining, vector<int> &nums, int &k)
    {
        //Base Case: at last we will ignore the spaces so here we pay 0 cost
        if(index == nums.size()) return 0;
        // if we already had calculated then simply return it
        if(dp[index][remaining] != -1) return dp[index][remaining];
        
        int ans;
        // when we don't have choices bcoz if we fill nums[index] here then 
        // it will disobey the limit so we here we seperate line and go to new line
        if(nums[index] > remaining)
        {
            // our 'remaining' exclude a space seperator but 
            // if this is last then we have to count that space in 'remaining' as well
            ans = (remaining + 1) * (remaining + 1) ;
            // k - nums[index] -1 = 'remaining',
            // when we fill next line by nums[index] and a space
            ans +=  solve(index + 1, k - nums[index] - 1, nums, k);
        }
        // Otherwise we have 2 choices
        else
        {
            // either we fill next word into new line
            int choice1 = (remaining + 1) * (remaining + 1) + solve(index + 1, k - nums[index] - 1, nums, k); 
            // or we fill in same line
            int choice2 = solve(index + 1, remaining - nums[index] - 1, nums, k);
            // we have to minimize the answer
            ans = min(choice1,choice2);
        }
        dp[index][remaining] = ans;
        return dp[index][remaining] ;
    }
public:
    int solveWordWrap(vector<int>nums, int k) 
    { 
        // Code here
        memset(dp,-1,sizeof dp);
        return solve(0,k, nums , k);
    } 
0
sushovansaha3 days ago
Memoization and Tabulation:
#include <bits/stdc++.h>

using namespace std;

int square(int n)
{
    return n * n;
}

int solve(vector<int> words, int n, int k, int idx, int remL, vector<vector<int>> &dp)
{
    // base case for last word
    if (idx == n - 1)
    {
        return words[idx] < remL ? 0 : square(remL);
    }

    if (dp[idx][remL] != -1)
    {
        return dp[idx][remL];
    }

    int cur = words[idx];
    // if word can fit in the remaining line
    if (cur < remL)
    {
        int len = (remL == k) ? (remL - cur) : (remL - cur - 1);
        return dp[idx][remL] = min(solve(words, n, k, idx + 1, len, dp), square(remL) + solve(words, n, k, idx + 1, k - cur, dp));
    }
    else
    {
        // if word is kept on next line
        return dp[idx][remL] = square(remL) + solve(words, n, k, idx + 1, k - cur, dp);
    }
}

int solveWordWrap(vector<int> nums, int k)
{
    int n = nums.size();

    vector<vector<int>> dp(n + 1, vector<int>(k + 1, -1));

    return solve(nums, n, k, 0, k, dp);
}

int solveWordWrap(vector<int> nums, int k)
{
    int n = nums.size();

    vector<vector<int>> dp(n + 1, vector<int>(k + 1, 0));

    for (int i = n; i >= 0; i--)
    {
        for (int j = 0; j <= k; j++)
        {
            if (i == n)
            {
                dp[i][j] = nums[i - 1] < j ? 0 : square(j);
            }
            else
            {
                int cur = nums[i - 1];
                // if word can fit in the remaining line
                if (cur < j)
                {
                    int len = (j == k) ? (j - cur) : (j - cur - 1);
                    dp[i][j] = min(dp[i + 1][len], square(j) + dp[i + 1][k - cur]);
                }
                else
                {
                    // if word is kept on next line
                    dp[i][j] = square(j) + dp[i + 1][k - cur];
                }
            }
        }
    }

    return dp[0][k];
}
+1
ruchitchudasama1236 days ago
public:
int dp[505][2005];
    int solve(int ind,int rem,vector<int> &nums,int k){
        if(ind==nums.size())return 0;
        
        if(dp[ind][rem]!=-1)return dp[ind][rem];
        
        // int cost;
        if(nums[ind]>rem){
            return dp[ind][rem]=pow(rem+1,2)+solve(ind+1,k-nums[ind]-1,nums,k);
        }
        
        
        int choice1=solve(ind+1,rem-nums[ind]-1,nums,k);
        
        int choice2=pow(rem+1,2)+solve(ind+1,k-nums[ind]-1,nums,k);
        
        return dp[ind][rem]=min(choice1,choice2);
    }
    int solveWordWrap(vector<int>nums, int k) 
    { 
        int n=nums.size();
        memset(dp,-1,sizeof dp);
        return solve(0,k,nums,k);
    }
0
aakashyadav101ay6 days ago
int solve(int ind, int rem, vector<int>& nums, int k, vector<vector<int>> &dp){       if(ind == nums.size()){           return 0;       }       if(dp[ind][rem] != -1){           return dp[ind][rem];       }       int cost = pow(rem, 2);              // if there is not enough space for 2nd word
       if(rem <= nums[ind]){           // adding the cost bz putting the 2nd word in next line 
           return dp[ind][rem] = cost + solve(ind+1, k-nums[ind], nums, k, dp);       }       // there is space left for next word           // either putting the word in the same line or in the next to reduce cost
           return dp[ind][rem] =         min(cost+ solve(ind+1, k-nums[ind],nums, k, dp ),                           solve(ind+1, rem-nums[ind]-1, nums, k, dp));          }   int solveWordWrap(vector<int>nums, int k)    {        vector<vector<int>> dp(nums.size(), vector<int> (k+1, -1));       return solve(1, k-nums[0],nums, k, dp);   }
+1
msa27041 week ago
class Solution {
    int help(vector<int>& nums, int i, int left, int k, vector<vector<int>>& memo){
        if(i==nums.size()){
            return 0;
        }
        if(memo[i][left]!=-1) return 		memo[i][left];
        int cost=pow(left,2);
        if(left<=nums[i]) return memo[i][left]=cost+help(nums,i+1,k-nums[i],k,memo);
        return memo[i][left]=min(cost+help(nums,i+1,k-nums[i],k,memo),help(nums,i+1,left-nums[i]-1,k,memo));
    }
public:
    int solveWordWrap(vector<int>nums, int k) 
    { 
        // Code here
        vector<vector<int>> memo(nums.size(),vector<int>(k+1,-1));
        return help(nums,1,k-nums[0],k,memo);
    } 
0
mrunaldeoles971 week ago
Need help in figuring out bug.
 
This it the solution I came up with.
class Solution
{
    public int solveWordWrap (int[] nums, int k)
    {
        return solveWordWrap(0,nums,k);
    }
    
    private int solveWordWrap(int startIndx, int[] nums, int k){
        
        if(startIndx >= nums.length-1)
            return 0;
        
        int min = Integer.MAX_VALUE;
        
        int charCount = 0;
        int words = 0;
        for(int i = startIndx; i < nums.length; i++){
            charCount = charCount + nums[i];
            words++;
            if(charCount+words-1 <= k)
                min = Math.min( (int)Math.pow(k - (charCount+ words-1),2) + solveWordWrap(i+1,nums,k),min);
            else
                break;
        }
        
        return min;
    }
}

For the input
nums = {10,6,5,3,1,10,8,2}
k = 12
The correct solution is 45, but my code is outputting 46.
0
rahulmahotra2 weeks ago
CODE ERROR OR PLATFORM ERROR?
If i declare my dp array globally then answer code is giving correct output but if i pass it by reference, 0 is being printed.
Can someone tell what is wrong.

    int f(vector<int>& nums, int k, int i, int rem, vector<vector<int>>& dp){
        
        if(i == nums.size()) return 0;
        
        if(dp[i][rem] != -1) return dp[i][rem];
        
        if(nums[i] > rem){
            
            return dp[i][rem] = pow(rem+1, 2) + 
                                 f(nums, k, i+1, k-nums[i]-1, dp);
            
        }
        
        int ch1 = pow(rem+1, 2) + f(nums, k, i+1, k-nums[i]-1, dp);
        int ch2 = f(nums, k, i+1, rem-nums[i]-1, dp);
        
        return dp[i][rem] = min(ch1, ch2);
        
    }
    
    int solveWordWrap(vector<int> nums, int k) 
    { 
        vector<vector<int>> dp(nums.size()+1, vector<int>(k+1, -1));
        return f(nums, k, 0, k, dp);
    } 

Globally, giving correct output

int dp[505][2005];
    int f(vector<int>& nums, int k, int i, int rem){
        
        if(i == nums.size()) return 0;
        
        if(dp[i][rem] != -1) return dp[i][rem];
        
        if(nums[i] > rem){
            
            return dp[i][rem] = pow(rem+1, 2) + 
                                 f(nums, k, i+1, k-nums[i]-1);
            
        }
        
        int ch1 = pow(rem+1, 2) + f(nums, k, i+1, k-nums[i]-1);
        int ch2 = f(nums, k, i+1, rem-nums[i]-1);
        
        return dp[i][rem] = min(ch1, ch2);
        
    }
    
    int solveWordWrap(vector<int> nums, int k) 
    {
        memset(dp, -1, sizeof dp);
        return f(nums, k, 0, k);
    } 
0
shashankpal1909
This comment was deleted.
0
ksheeragrawal3 weeks ago
class Solution {public:   int solveWordWrap(vector<int>nums, int k)    {      int n=nums.size();     int dp[n+1];     dp[n]=0;     dp[n-1]=0;     if(n==1){return 0;}          for(int i=n-2;i>=0;i=i-1)     {         int curr=nums[i];         dp[i]=dp[i+1]+(k-nums[i])*(k-nums[i]);                   int aja=1;         while(aja<n-i)         {                curr=curr+nums[i+aja]+1;                       if(curr<=k)             {   if(i+aja==n-1){dp[i]=0;}                 else{dp[i]=min(dp[i],(k-curr)*(k-curr)+dp[i+aja+1]);}             }             else{break;}            aja=aja+1;         }     }     return dp[0];   } };
0
sidheshwarsaravanan3 weeks ago
Python solution [DP]
Top down recursive DP 
class Solution:
def solveWordWrap(self, nums, k):
       n = len(nums)
       dp = [[-1] * (k+1) for _ in range(n+1)]
       def recurse(index, cur_limit):
           if index == n:
               return 0
           if dp[index][cur_limit] != -1:
               return dp[index][cur_limit]
           if nums[index] <= cur_limit:
               take = recurse(index + 1, cur_limit - nums[index] - 1)
               not_take = (cur_limit + 1) * (cur_limit + 1) + recurse(index + 1, k - nums[index] - 1)
               dp[index][cur_limit] = min(take, not_take)
           else:
               not_take = (cur_limit + 1) * (cur_limit + 1) + recurse(index + 1, k - nums[index] - 1)
               dp[index][cur_limit] = not_take
           return dp[index][cur_limit]
       return recurse(0, k)
 
 
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.