Text Justification

Level: Advanced

Concepts: Strings Algorithms


Create a program that justifies text to fit a specified width.

Requirements

  1. Implement text justification rules:
    • Break text into lines of specified width
    • Distribute spaces evenly between words
    • Left-align the last line of text
    • Handle single words per line
  2. Handle edge cases:
    • Empty input
    • Input shorter than line width
    • Words longer than line width
    • Multiple consecutive spaces
  3. Return appropriate results:
    • Justified text as an array of strings
    • Error message for invalid inputs

Test Cases

Input Width Expected Output Notes
"This is a test" 16 ["This is a", "test"] Even space distribution
"This is a test" 14 ["This is a", "test"] Uneven space distribution
"This is a test" 20 ["This is a test"] No justification needed
"This is a very long word" 10 ["This is a", "very long", "word"] Multiple line breaks
"Word" 10 ["Word"] Single word
"This is a test" 16 ["This is a", "test"] Handle multiple spaces

Edge Cases to Consider

  • Empty string
  • Null input
  • Zero or negative width
  • Very long words
  • Multiple consecutive spaces or tabs
  • Text with line breaks

Tips

  • Start with simple cases (no justification needed)
  • Add basic line breaking next
  • Then implement space distribution
  • Finally add special case handling
  • Consider using a helper method for space distribution