Plain-Text to HTML: Paragraphs, Blockquotes, and Strikethrough
StringsModel answerLast updated
Write a function that converts a plain-text string to HTML with paragraphs, soft line breaks, blockquotes, and strikethrough, handling all edge cases correctly.
Plain-Text to HTML: Paragraphs, Blockquotes, and Strikethrough
Write a function render(text: str) -> str that turns a plain-text string into an HTML string. Support exactly the four features below and nothing else.
Feature specification
1. Paragraphs
One or more blank lines (lines that are empty or contain only whitespace) act as paragraph separators. Wrap each paragraph in <p>…</p>. Never emit an empty <p></p> for leading, trailing, or consecutive blank lines.
2. Soft line breaks
A single newline between two non-blank lines within the same paragraph becomes <br/> in the output.
3. Blockquotes
A run of consecutive lines where every line begins with "> " (a > immediately followed by a space, at column 0) forms one <blockquote>…</blockquote>. Before rendering, strip the leading "> " from each such line. Soft line breaks inside a blockquote also become <br/>. A blank line ends the blockquote. Blockquotes are siblings of <p> elements — never nested inside one. A line like ">no space" or " > x" is plain text, not a blockquote line.
4. Strikethrough
A matched pair of ~~ markers wrapping non-empty content becomes <del>…</del>. For example: ~~like this~~ → <del>like this</del>. An opener with no matching closer in the same block stays as literal text. An empty pair ~~~~ also stays literal.
5. Inline markup is block-scoped
A ~~ that opens in one block and never closes within that same block is treated as plain text. Markup cannot cross paragraph or blockquote boundaries.
The output must be valid HTML. HTML special characters in the input (<, >, &) must be escaped.
What your answer should cover
- Your overall strategy: how you divide the problem into block-level and inline-level phases.
- How you group lines into blocks in a single linear scan.
- How you process inline markup within each block.
- Time and space complexity in terms of input length n.
- How you handle each of the following edge cases:
- The empty string and strings that contain only newlines.
- Trailing whitespace on content lines.
- Whitespace-only lines acting as paragraph separators.
- A run of lines that alternates between quoted and plain lines.
- Two blockquote groups separated by a blank line.
- A
">..."line missing the required space after>. - An unmatched or empty
~~pair. - A
~~pair that would need to span a paragraph boundary. - Input containing
<,>, or&.
Example input
This is a paragraph with a
soft line break.
> Some quoted text
> continues here
This has a ~~strikethrough~~ word.
Expected output
<p>This is a paragraph with a<br/>soft line break.</p>
<blockquote>Some quoted text<br/>continues here</blockquote>
<p>This has a <del>strikethrough</del> word.</p>
Include at least five test cases that exercise the edge cases listed above.
Hints
Hint 1
Separate the work into two independent phases: a line-level pass that groups lines into typed blocks (paragraph or blockquote), and a character-level pass that applies inline markup within each block. This separation makes the 'no cross-block markup' rule free — the inline scanner never sees a block boundary.
Hint 2
During the line scan, maintain a current block kind and a line buffer. Three events should flush the buffer and emit an element: a blank line, a change in line kind (e.g., a quoted line appears after a plain one), and end of input. Flush before switching kinds so you never mix content.
Hint 3
For the strikethrough scan, walk left to right through the block text. Each time you find an opener `~~`, immediately search forward for the next `~~` as the closer. If no closer exists in the current block, emit everything from the opener to the end as literal text and stop. This greedy left-to-right pairing handles consecutive pairs like `~~a~~ ~~b~~` correctly and runs in O(n).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Strategy: two-level parsing
The cleanest way to approach this is to split parsing into two levels that never interfere with each other.
Block level: scan lines one at a time and group them into typed blocks — either a <p> block or a <blockquote> block. Block boundaries are determined by blank lines and by line-kind changes.
Inline level: once a block's lines are collected, join them and process inline markup (strikethrough). The inline scanner operates on a single block's text and never crosses a boundary, so the "markup cannot span blocks" rule falls out naturally with no special cases.
Phase 1: grouping lines into blocks
Iterate over lines. For each line:
- Strip trailing whitespace. If the result is empty, it is a blank separator — flush the current buffer and continue.
- If the line starts with
"> "(two specific characters at column 0), it belongs to ablockquoteblock; strip the prefix before buffering. - Otherwise it belongs to a
pblock. - If the new line's kind differs from the current block's kind, flush first, then start the new block.
At end of input, flush whatever remains.
A flush that finds an empty buffer is a no-op, which prevents empty <p></p> elements from appearing at the start or end of the input.
A few contract decisions worth stating before writing code:
- A line like
">no space"does not match the"> "rule and is emitted as plain text (escaped to>no space). - A whitespace-only line counts as blank, so
"a\n \nb"produces two paragraphs. - When a paragraph alternates between quoted and plain lines, each contiguous same-kind run becomes its own element: plain → blockquote → plain produces
<p>,<blockquote>,<p>. - Two blockquote groups separated by a blank line become two separate
<blockquote>elements, consistent with "blockquotes cannot span paragraphs."
Phase 2: inline rendering
For each flushed block, join the buffered lines with "\n", then:
- HTML-escape first. Replace
&→&,<→<,>→>. This step must come before tag injection is possible. - Pair
~~markers left to right. Scan forward for an opener. From there, scan forward for a closer. If a closer exists and the content between them is non-empty, wrap it in<del>…</del>. If no closer exists, or the pair is empty (~~~~), emit the characters literally and advance. Resume scanning after the closer. - Replace bare newlines with
<br/>. This is done last so the<br/>strings themselves don't participate in the~~scan.
Complexity
Time: O(n). The line split and grouping are a single pass. In the inline scan, each find call starts where the previous one ended, so no character is visited twice per block, and the sum across all blocks is linear in n.
Space: O(n) for the line list, block buffers, and the output.
Edge case reference
| Input | Output |
|---|---|
"" or "\n\n" | "" — flush on empty buffer is a no-op |
"hi \n " | <p>hi</p> — trailing spaces stripped; second line becomes blank |
"a\n \nb" | <p>a</p><p>b</p> — whitespace-only line is a separator |
"> a\n\n> b" | <blockquote>a</blockquote><blockquote>b</blockquote> |
"x\n> q\ny" | <p>x</p><blockquote>q</blockquote><p>y</p> |
">no space" | <p>>no space</p> |
"~~~~" | <p>~~~~</p> — empty pair stays literal |
"a ~~b" | <p>a ~~b</p> — unmatched opener is literal |
"~~open\n\nclose~~" | <p>~~open</p><p>close~~</p> — blank line ends block before closer |
"1 < 2 & 3" | <p>1 < 2 & 3</p> |
Solution
import html
def _escape(s: str) -> str:
return html.escape(s, quote=False)
def _render_inline(text: str) -> str:
"""
HTML-escape text, replace matched non-empty ~~...~~ pairs with <del>,
then convert bare newlines to <br/>. Unmatched or empty ~~ stays literal.
"""
parts = []
i = 0
n = len(text)
while i < n:
opener = text.find("~~", i)
if opener == -1:
break
closer = text.find("~~", opener + 2)
if closer == -1:
break # no closer — rest is literal
if closer == opener + 2: # empty pair "~~~~" — keep literal
parts.append(_escape(text[i : closer + 2]))
i = closer + 2
continue
# valid non-empty pair
parts.append(_escape(text[i:opener]))
parts.append("<del>" + _escape(text[opener + 2 : closer]) + "</del>")
i = closer + 2
parts.append(_escape(text[i:]))
return "".join(parts).replace("\n", "<br/>")
def render(text: str) -> str:
lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
out: list[str] = []
kind: str | None = None # "p" or "blockquote"
buf: list[str] = []
def flush() -> None:
nonlocal kind, buf
if kind is None:
return
body = _render_inline("\n".join(buf))
if kind == "blockquote":
out.append(f"<blockquote>{body}</blockquote>")
else:
out.append(f"<p>{body}</p>")
kind, buf = None, []
for raw_line in lines:
stripped = raw_line.rstrip()
if stripped == "": # blank line — block boundary
flush()
continue
if stripped.startswith("> "):
line_kind = "blockquote"
content = stripped[2:]
else:
line_kind = "p"
content = stripped
if line_kind != kind: # kind switch — flush before starting new block
flush()
kind = line_kind
buf.append(content)
flush()
return "".join(out)
Test cases
# Provided example
sample = (
"This is a paragraph with a\nsoft line break.\n\n"
"> Some quoted text\n> continues here\n\n"
"This has a ~~strikethrough~~ word."
)
assert render(sample) == (
"<p>This is a paragraph with a<br/>soft line break.</p>"
"<blockquote>Some quoted text<br/>continues here</blockquote>"
"<p>This has a <del>strikethrough</del> word.</p>"
)
# Empty and whitespace-only inputs
assert render("") == ""
assert render("\n\n\n") == ""
# Trailing whitespace stripped; whitespace-only line is a separator
assert render("hi \n \n") == "<p>hi</p>"
assert render("a\n \nb") == "<p>a</p><p>b</p>"
# Two blockquote groups separated by a blank line
assert render("> a\n\n> b") == "<blockquote>a</blockquote><blockquote>b</blockquote>"
# Kind change mid-paragraph
assert render("x\n> q\ny") == "<p>x</p><blockquote>q</blockquote><p>y</p>"
# Missing space after > — not a blockquote
assert render(">no space") == "<p>>no space</p>"
# Strikethrough edge cases
assert render("~~a~~ and ~~b~~") == "<p><del>a</del> and <del>b</del></p>"
assert render("~~~~") == "<p>~~~~</p>"
assert render("a ~~b") == "<p>a ~~b</p>"
# Cross-paragraph ~~ is literal on both sides
assert render("~~open\n\nclose~~") == "<p>~~open</p><p>close~~</p>"
# HTML escaping
assert render("1 < 2 & 3") == "<p>1 < 2 & 3</p>"
Common mistakes to avoid
- Skipping HTML escaping. Input containing
<,>, or&will produce invalid HTML or allow tag injection. Escape before building any tags. - Trying to handle block and inline rules in one state machine. It works, but the resulting state explosion makes edge cases like
~~~~and kind-switching inside a paragraph very hard to reason about. The two-phase design is simpler and just as fast. - Forgetting that
"> "requires a space.">x"is plain text. The rule is exactly two leading characters. - Emitting
<br/>before the strikethrough scan. If you replace newlines first, the<br/>string becomes part of the text the~~scanner sees, which complicates the logic unnecessarily. - Treating
~~~~as a valid empty<del></del>. The spec says empty content is not valid strikethrough, so both tildes stay literal.