Katkat

Format words into wrapped/justified lines

SoFiSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to implement a greedy word-wrapping algorithm that packs words into lines of a fixed width while managing spacing constraints.

Problem: Line Justification

Given a list of words (as a list of strings) and a maximum line width k, format the text such that each line contains as many words as possible without exceeding k characters. Each word on a line must be separated by at least one space.

Requirements

  1. For each line, pack words greedily until adding the next word would exceed k.
  2. Do not split words between lines.
  3. Return a list of strings where each string is a formatted line.

Function Signature

def justify_text(words: List[str], k: int) -> List[str]:

Examples

Example 1: Input: words = ["This", "is", "an", "example", "of", "text", "justification."], k = 16 Output:

[
  "This is an",
  "example of text",
  "justification."
]

Example 2: Input: words = ["a", "b", "c"], k = 3 Output:

[
  "a b",
  "c"
]

Constraints

  • 1 <= len(words) <= 1000
  • 1 <= len(words[i]) <= k
  • Words contain only alphanumeric characters.
  • If a single word is longer than k, you may assume it stays on its own line (or is truncated, depending on how you handle the constraint).

Edge Cases

  • The list contains only one word.
  • All words are exactly k length.
  • The total length of words plus required spaces equals exactly k.

Hints

Hint 1

Iterate through the list of words and keep a running total of the current line's length, including the mandatory spaces between words.

Hint 2

When adding a new word exceeds `k`, finalize the current line and start a new one using the word that didn't fit.

Hint 3

Be careful to track the length of the current line correctly so that you don't add a trailing space at the end of each line.

Follow-up questions

  • How would you modify your solution to 'fully justify' the text, where spaces are distributed evenly between words so that every line (except the last) has exactly `k` characters?
  • What is the time and space complexity of your approach in terms of the total number of characters and the number of words?
  • How would you handle a case where a single word provided in the input is longer than the width `k`?