Wrap Subtitle Lines to Minimize Ragged Right Edges

Last updated: November 29, 2026

Quick Overview

Given the words of a subtitle cue and a maximum line width in characters, break the words into lines so no line exceeds the width and the sum of squared unused characters on every line except the last is minimized; return the lines.

Disney
Coding & Algorithms
Software Engineer
Disney
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given the words of a subtitle cue and a maximum line width in characters, break the words into lines so no line exceeds the width and the sum of squared unused characters on every line except the last is minimized; return the lines.

A dynamic programming round in the style of Disney Streaming player and localization teams, who render subtitles in dozens of languages on screens from phones to TVs. The interviewer checks that you reject greedy wrapping, define a clean DP state, and reconstruct the answer.

What the Interviewer Expects
  • Show why greedy line filling is not optimal for squared slack
  • Define dp[i] as the best cost for words i onward
  • Exclude the last line from the cost
  • Store the break choice to rebuild the lines
  • Give O(n x W) time where W bounds words per line
Key Topics to Cover
dynamic programming
text layout
reconstruction
greedy vs DP
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you handle languages without spaces, such as Japanese?
  • Subtitles are limited to two lines; how does the DP change?
  • How would you measure width in rendered pixels instead of characters?
  • Can you avoid splitting a name like "Mickey Mouse" across lines?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: list of words and width. Words are separated by single spaces and never split. Cost of a non-final line is (width - line_length)^2; the final line is free. Output: the lines and the total c...

High-Level Design

Greedy filling can leave one very short line later, and squaring the slack punishes that, so greedy is not optimal. Let cost[i] be the minimal cost to lay out words[i:]. For each i, try putting ...


Submit Your Answer
Markdown supported

Related Questions