Implementing Text Justification with Dynamic Programming
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Text justification is a common problem in typesetting and word-processing applications, where the goal is to distribute text evenly across lines so that both the left and right edges are aligned. Dynamic Programming provides an optimal solution to handle the text justification problem by considering different ways to break up text into lines while minimizing raggedness.
Problem Definition
Consider you have a paragraph of text that needs to be split into multiple lines of a specific width, `L`. The task is to adjust the spacing between words so that each line (except possibly the last line) is fully justified.
Key Objectives:
- Minimize the "cost" associated with a poorly justified paragraph.
- Ensure each line does not exceed the maximum width, `L`.
Dynamic Programming Approach
Dynamic Programming (DP) is particularly suitable for this problem because it enables you to break down the problem into simpler subproblems, solve each subproblem just once, and store their solutions, typically in an array or table, to avoid redundant calculations.
Steps:
- Calculate Badness (Cost) of Each Line: Define the "badness" of a line as a function of the extra spaces at the end of the line. Usually, we define:
- Base Case and Recurrence:
- Use a 1-based index for words.
- `dp[j]` holds the minimum cost of justifying the first `j` words.
- Base Case: `dp[0] = 0` (No words means no cost) Recurrence relation:
- Complexity:
- Precompute the cost of each line and store in a 2D matrix, `cost[i][j]`.
- Update `dp` array iteratively beginning from the first word.
- The time complexity is typically , which is feasible for moderate values of `n`.
Example Implementation:
Here is a Python function to illustrate the DP approach for text justification:
- Single word lines.
- Large gaps due to short lines or paragraph endings.
- Handling hyphenation (optional for basic implementations).
Related reading
- Implementing the Spigot algorithm for `π` pi
- Impossible-to-find bug in a program that equalizes wealth in a group UVA 10137, The Trip
- Improve algorithmic thinking
- Improving performance of click detection on a staggered column isometric grid
- Improving search result using Levenshtein distance in Java
- In-order iterator for binary tree
- In-place array reordering?
- In-place interleaving of the two halves of a string

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.