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
+2
hacky32441 week ago
int dp[501];   int n;   int k;   int recur(int i,int j,vector<int>&nums){       if(i>=n){           return 0;       }       if(dp[i]!=-1)return dp[i];       int su=0;       int ans=INT_MAX;       for(int j=i; j<n;j++){           su+=nums[j];           if(k-su<0)break;           if(j<n-1)           ans=min(ans,(k-su)*(k-su)+recur(j+1,j-i+1,nums));           else ans=0+recur(j+1,j-i+1,nums);                      su++;       }       return dp[i]=ans;   }   int solveWordWrap(vector<int>nums, int K)    {        // Code here       n=nums.size();       k=K;       memset(dp,-1,sizeof(dp));       int ans=recur(0,0,nums);             return ans;   } 
+4
rushabhrbs1 week ago
class Solution {   int solve(int ind ,int n , vector<int>& nums , int k , vector<int>& dp){       if(ind >= n )       return 0;       if(dp[ind] != -1)       return dp[ind];       int ans = INT_MAX;       int sum = 0 ;       for(int i = ind ; i < n ; i++){           sum += nums[i];           if(sum + (i - ind) <=k){               int cost = 0;               if(i != n - 1){                   cost = pow(k - sum - i + ind , 2);               }               ans = min(ans ,cost + solve(i + 1, n , nums , k , dp));                        }       }       return dp[ind] = ans;   }public:   int solveWordWrap(vector<int>nums, int k)    {        // Code here       int n = nums.size() ;       vector<int>dp(n , -1);       return solve(0 , n , nums , k , dp);   } }; 
0
anuragshubham341 week ago
class Solution{   public int solveWordWrap (int[] nums, int k)   {       int n=nums.length;       int[] dp=new int[n];       int cost=0,currlen;       dp[n-1]=0;       for(int i=n-2;i>=0;i--){           currlen=-1;           dp[i]=Integer.MAX_VALUE;           for(int j=i;j<n;j++){               currlen+=(nums[j]+1);               if(currlen>k)               break;               if(j==n-1)                cost=0;               else                cost=(k-currlen)*(k-currlen)+dp[j+1];                                  if(cost<dp[i])                   dp[i]=cost;           }       }      // for(int x:dp)      //  System.out.println(x);     return dp[0];     }}
0
harshidsahare201 week ago
int solve(int ind ,int n , vector<int>& nums , int k , vector<int>& dp){
        if(ind >= n )
        return 0;
        if(dp[ind] != -1)
        return dp[ind];
        int ans = INT_MAX;
        int sum = 0 ;
        for(int i = ind ; i < n ; i++){
            sum += nums[i];
            if(sum + (i - ind) <=k){
                int cost = 0;
                if(i != n - 1){
                    cost = pow(k - sum - i + ind , 2);
                }
                ans = min(ans ,cost + solve(i + 1, n , nums , k , dp));
              
            }
        }
        return dp[ind] = ans;
    }

    int solveWordWrap(vector<int>nums, int k) 
    { 
        // Code here
        int n = nums.size() ;
        vector<int>dp(n , -1);
        return solve(0 , n , nums , k , dp);
    } 
 
 
0
satiitmadras1231 week ago
class Solution {public:   int dp[501][2001];   int helper(vector<int>&nums,int idx,int k,int currCount)   {       if(idx >= nums.size()) return 0;       if(dp[idx][currCount]!=-1) return dp[idx][currCount];       if(idx == nums.size()-1)       {           if(currCount+nums[idx] <= k) return 0;                      int isLeft = pow(k-currCount+1,2);           return isLeft;       }              if(currCount+nums[idx] <= k)       {           int ifleft = pow(k-currCount+1,2);                      return dp[idx][currCount] = min(helper(nums,idx+1,k,currCount+nums[idx]+1),ifleft + helper(nums,idx+1,k,nums[idx]+1));       }       else       {           int ifleft = pow(k-currCount+1,2);           return dp[idx][currCount] = ifleft + helper(nums,idx+1,k,nums[idx]+1);       }   }   int solveWordWrap(vector<int>nums, int k)    {        // Code here       memset(dp,-1,sizeof(dp));       return helper(nums,0,k,0);   } };
0
sksirajsj2 weeks ago
class Solution {
public:
   //rec(i,k,v) returns min cost in range [0,i];
   int dp[510];
   int n;
   int rec(int i,int k,vector<int>& v){
   		//base case
       if(i<0)return 0;
       //check if already calculated
       if(dp[i]!=-1)return dp[i];
       int cost = 0,ans=1e9,pref=0;
       //transitions
       for(int j=i;j>=0;j--){
           pref+=v[j];
           if((pref+(i-j))<=k){
               if(i!=(n-1)){
                   cost = (k-(pref+i-j))*(k-(pref+i-j));
               }
               ans = min(ans,rec(j-1,k,v)+cost);
           }
       }
       return dp[i] = ans;
   }
   
   int solveWordWrap(vector<int>nums, int k) 
   { 
       // Code here
       memset(dp,-1,sizeof(dp));
       n = nums.size();
       return rec(n-1,k,nums);
   } 
};
+7
spideyyy1092 weeks ago
difficulty level should be hard . 
0
sandeepgattani2 weeks ago
JAVA solution:
    private int getCost(int[] nums, int from, int to, int k){       if(to == nums.length-1) return 0;              int used = 0;              for(int i=from; i<=to; i++){           if(used > 0) used++;           used += nums[i];           }              return (k-used)*(k-used);   }      public int solveWordWrapRec (int[] nums, int k, int idx, Map<Integer, Integer> cache){       if(idx >= (nums.length-1)){           return 0;       }              Integer value = cache.get(idx);       if(value != null) return value;              int cost = Integer.MAX_VALUE;       int used = 0;              for(int i=idx; i<nums.length; i++){           if(used+nums[i] > k) break;                      if(i+1 < nums.length){               cost = Math.min(cost, solveWordWrapRec(nums, k, i+1, cache) + getCost(nums, idx, i, k));           }else{               cost = Math.min(cost, getCost(nums, idx, i, k));           }                      used += nums[i] + 1;       }              value = cost;       cache.put(idx, value);              return value;   }
 
    public int solveWordWrap (int[] nums, int k)   {       return solveWordWrapRec(nums, k, 0, new HashMap<>());   }
 
+1
sourav1919sharma2 weeks ago
int square(int n){
        return n * n;
    }
    
    int helper(vector<int>&word, int n, int length, int wordIndex, int remLength, vector<vector<int>>&dp){
        //We are at the last word
        if(wordIndex == n - 1){
            //If there is required space left in the currline
            if(word[wordIndex] < remLength){
                return 0;
            }
            //Otherwise insert it in the next line and return the cost which is square of white space
            return square(remLength);
        }
        
        if(dp[wordIndex][remLength] != -1)
            return dp[wordIndex][remLength];
        
        int currWord = word[wordIndex];
        
        //If word can fit in the remaining line
        if(currWord < remLength){
            /*
            Case 1: Insert it in the same line
            (remLength == length) ==> 
            whether we are putting the first word in the line
                -> If this is the case then we dont need to add one extra space
            or we are putting next word in the same line
                -> If this is the case then we need to insert extra space between
                the two words.
            */
            int insert = helper(word, n, length, wordIndex + 1, remLength == length 
                                    ? remLength - currWord : remLength - currWord - 1, dp);
                                    
            //Case 2: Insert it in the next line.
            int dontInsert = square(remLength) + helper(word, n, length, wordIndex + 1, length - currWord, dp);
            
            return dp[wordIndex][remLength] = min(insert, dontInsert);
        }
        
        //We don't have any choice so insert the word in the next line.
        return dp[wordIndex][remLength] = square(remLength) + helper(word, n, length, wordIndex + 1, length - currWord, dp);
    }

    int solveWordWrap(vector<int>nums, int k){
        vector<vector<int>>dp(nums.size(), vector<int>(k + 1, -1));
        return helper(nums, nums.size(), k, 0, k, dp);
    } 
+8
pritamkr2122 weeks ago
THIS IS A BEAUTIFUL QUESTION OF DP DONT FORGET TO BOOKMARK
TO GET THE INTUTION U KNOW THE GAP METHOD(DIAGONAL TRAVERSAL) WHICH IS A BEST TOOL IN DP QUESTIONS . SO STEPS TO GRAPS THIS QUESTION 
 1-→https://youtu.be/lvRdFCMD_Ew WATCH AT(1.75X)
 2-→https://youtu.be/FiQY3K4_xPo NICE EXPLANTION(WATCH FOR INTUTION)
OTHER DOCUMENTATION -→https://www.geeksforgeeks.org/word-wrap-problem-space-optimized-solution/ best solution
 
class Solution
{
    public int solveWordWrap (int[] a, int k)
    {
        int[][]dp=new int[a.length][a.length];
        for(int gap=0;gap<dp.length;gap++){
            for(int i=0,j=gap;j<dp.length;j++,i++){
                if(gap==0){
                    dp[i][j]=k-a[i];
                }
                else{
                    dp[i][j]=dp[i][j-1]-a[j]-1;
                }
            }
        }
        for(int i=0;i<dp.length;i++)
        {
            for(int j=i;j<dp.length;j++)
            {
                if(dp[i][j] < 0)dp[i][j] = Integer.MAX_VALUE;
                else if(j== a.length-1)dp[i][j]=0;
                else dp[i][j] = (int)Math.pow(dp[i][j], 2);
            }
        }
        
        int[]ans=new int[a.length];
        for(int i=dp.length-1;i>=0;i--){
            ans[i]=dp[i][dp.length-1];
            for(int j=dp.length-1;j>i;j--){
                if(dp[i][j-1]==Integer.MAX_VALUE)continue;
                else if(ans[i]>ans[j]+dp[i][j-1]){
                    ans[i]=ans[j]+dp[i][j-1];
                }
            }
        }
        return ans[0];
    }
}
 
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.