Problem · String

Format Text

MediumTiktokFULLTIMEOA
See Tiktok hiring insights

Given multiple paragraphs, their alignment (LEFT or RIGHT), and a maximum line width, format the text like a newspaper: pack words greedily into lines, pad spaces according to alignment, and add a border of * around the entire output.

Rules:

  • For each paragraph, pack as many words as possible into each line without exceeding width (greedy, using two pointers).
  • If alignment is LEFT: pad trailing spaces so each line is exactly width characters.
  • If alignment is RIGHT: pad leading spaces so each line is exactly width characters.
  • Wrap all lines with a * border: one * on each side of every content line, plus a full row of * characters on the top and bottom. The total line width (including border characters) is width + 2.

Return the formatted output as a list of strings.

Examples
01 · Example 1
paragraphs = ["abc"]
alignments = ["LEFT"]
width = 3
return = ["*****","*abc*","*****"]
width=3, border line = "*****" (width+2=5 stars). The single word "abc" fills the line exactly. With LEFT alignment no extra padding is needed. Output: top border, content line "*abc*", bottom border.
02 · Example 2
paragraphs = ["hello world"]
alignments = ["LEFT"]
width = 7
return = ["*********","*hello  *","*world  *","*********"]
width=7, border line = "*********" (9 stars). "hello" (5) + " world" would exceed 7, so they wrap to separate lines. Each is LEFT-padded with trailing spaces to fill 7 chars: "hello " and "world ". Content lines become "*hello *" and "*world *".
More Tiktok problems
drafts saved locally
public List<String> formatText(String[] paragraphs, String[] alignments, int width) {
  // write your code here
}
paragraphs["abc"]
alignments["LEFT"]
width3
expected["*****","*abc*","*****"]
sign in to submit