Problem · String
Format Text
Learn this problemProblem statement
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 exactlywidthcharacters. - If alignment is
RIGHT: pad leading spaces so each line is exactlywidthcharacters. - 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) iswidth + 2.
Return the formatted output as a list of strings.
Function
formatText(paragraphs: String[], alignments: String[], width: int) → List<String>Examples
Example 1
paragraphs = ["abc"]alignments = ["LEFT"]width = 3return = ["*****","*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.
Example 2
paragraphs = ["hello world"]alignments = ["LEFT"]width = 7return = ["*********","*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
- Can Reach the Exit with TeleportsOA · Seen Jul 2026
- Check Monotonic TriplesOA · Seen Jul 2026
- Shift Every K-th ConsonantOA · Seen Jul 2026
- Count Access Code PairsOA · Seen Jul 2026
- Count Key ChangesOA · Seen Jul 2026
- Sort Matrix BordersOA · Seen Jul 2026
- Travel Distance on ScootersOA · Seen Jul 2026
- Validate 3x3 Digit WindowsOA · Seen Jul 2026