This is a premium problem. We're working on making it available for free soon.
Use these hints if you're stuck. Try solving on your own first.
Create an array storing all of the words in sentence separated.
Try dynamic programming.
Build a dp array where dp[i] represents the minimum total cost for the first i + 1 words.
Solutions for this premium problem will be available for free soon.
Browse Free ProblemsWatch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Dynamic programming works well because the problem has overlapping subproblems and optimal substructure. The best way to arrange words starting at one position depends on optimal solutions for later positions.
Problems involving text justification and row formatting with dynamic programming are common in coding interviews. Variants of this problem appear in interviews at large tech companies because they test DP reasoning and string manipulation skills.
An array-based dynamic programming table is the main data structure used. It stores the minimum cost for arranging words starting from each index, allowing efficient reuse of previously computed results.
The optimal approach uses dynamic programming. From each word index, try forming rows with subsequent words while staying within the width limit and compute the penalty cost. The minimum total cost is found by combining the row cost with the optimal result for the remaining words.