Back to Practice
#0225

Wrap Text Into Lines

MediumPython25 min20 XP

Problem

Given text and max_width, return lines where words stay in order and no line exceeds max_width.

Why This Matters

Text wrapping is a practical greedy problem that trains careful length accounting.

Function Signature

def wrap_text(text, max_width):

Examples

Example 1
Inputtext = "python makes clean code", max_width = 12
Output["python makes", "clean code"]

Adding "clean" to the first line would exceed width 12.

Constraints

  • Return the exact requested value.
  • Handle edge cases cleanly.
  • Prefer readable Python before micro-optimizing.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Inputtext = "python makes clean code", max_width = 12
Expected["python makes", "clean code"]

Adding "clean" to the first line would exceed width 12.

Hidden Test Categories
single wordmultiple spaces in inputexactly full line