InterviewDB Question

Display Strings: Format and Wrap Text to Fit a Fixed-Width Screen

Question Details

Problem

You are given a list of words and an integer width. Format the words into lines such that each line contains as many words as possible without exceeding width characters. Words on the same line are separated by a single space.

Return the list of formatted lines.

python
def display_strings(words: list[str], width: int) -> list[str]:
    pass

**Input**:  words = ["the", "quick", "brown", "fox", "jumps"], width = 12
Output: ["the quick", "brown fox", "jumps"]
# "the quick" = 9 chars (fits), "the quick brown" = 15 (too long)

**Input**:  words = ["hello", "world"], width = 5
Output: ["hello", "world"]
# Each word exactly fills the width

Follow-ups

  1. What if a single word is longer than width — should you truncate, split, or raise an error?
  2. Modify the solution to justify text fully: distribute extra spaces evenly between words on each line (last line left-aligned).
  3. How would you handle unicode characters that have display widths of 2 (e.g., CJK characters)?
  4. What is your time and space complexity?

Full Details

Problem

You are given a list of words and an integer width. Format the words into lines such that each line contains as many words as possible without exceeding width characters. Words on the same line are separated by a single space.

Return the list of formatted lines.

python
def display_strings(words: list[str], width: int) -> list[str]:
    pass

**Input**:  words = ["the", "quick", "brown", "fox", "jumps"], width = 12
Output: ["the quick", "brown fox", "jumps"]
# "the quick" = 9 chars (fits), "the quick brown" = 15 (too long)

**Input**:  words = ["hello", "world"], width = 5
Output: ["hello", "world"]
# Each word exactly fills the width

Follow-ups

  1. What if a single word is longer than width — should you truncate, split, or raise an error?
  2. Modify the solution to justify text fully: distribute extra spaces evenly between words on each line (last line left-aligned).
  3. How would you handle unicode characters that have display widths of 2 (e.g., CJK characters)?
  4. What is your time and space complexity?

About This Question

This is a reported interview question from a ziphq interview during the phone round.

It covers the following topics: Coding, Onsite, Phone, Strings .