Lightweight Markdown HTML Converter

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement markdown_to_html(text: str) -> str to render plain-text notes using a compact four-rule Markdown dialect into well-formed HTML:

  1. Paragraphs (<p>...</p>): Contiguous non-blank lines belong to a paragraph, while one or more blank lines (such as "\n\n", "\r\n\r\n", or lines containing only spaces/tabs) separate paragraphs. Leading, trailing, or repeated blank lines never produce empty <p></p> tags, and empty or whitespace-only input returns "". Leading and trailing whitespace on each line's content is trimmed.
  2. Line wraps (<br/>): A single line break between adjacent lines inside the same <p> or <blockquote> element becomes <br/> (any valid HTML break spelling <br>, <br/>, or <br /> and optional whitespace adjacent to block/break tags are accepted).
  3. Quoted blocks (<blockquote>...</blockquote>): One or more consecutive lines whose raw text starts with "> " (greater-than followed immediately by a space, checked before trimming) merge into one <blockquote>...</blockquote> with each line's leading "> " removed and internal wraps rendered as <br/>. Blank lines always split quoted blocks into separate <blockquote> elements. When a paragraph mixes quoted and unquoted lines without an intervening blank line, emit separate top-level <p>...</p> and <blockquote>...</blockquote> elements in sequence for each contiguous run rather than nesting <blockquote> inside <p>. Lines starting with ">" without a following space, or with spaces before "> ", are ordinary paragraph text.
  4. Strikethrough (<del>...</del>): Pairs of double tildes ~~...~~ that open and close within the same <p> or <blockquote> block render as <del>...</del> (and may span <br/> wraps inside that block). Delimiters never match across paragraph separators or across <p>/<blockquote> boundaries; single ~ characters or an unmatched ~~ with no closing ~~ later in the same block remain literal tilde characters.
  5. HTML entity escaping: Raw &, <, and > characters in text content (both outside and inside <del>) must be escaped as &amp;, &lt;, and &gt;.

Examples

Example 1

text = (
    "Deploy window opens at 09:00\n  and closes at 10:30.\n\n"
    "> Freeze main branch\n> monitor error rates\n\n"
    "Roll back ~~legacy v1~~ traffic."
)
markdown_to_html(text)

Output:

<p>Deploy window opens at 09:00<br/>and closes at 10:30.</p>
<blockquote>Freeze main branch<br/>monitor error rates</blockquote>
<p>Roll back <del>legacy v1</del> traffic.</p>

Walk-through: Blank lines split the text into three paragraphs. Paragraph 1 joins two trimmed lines with <br/> inside <p>. Paragraph 2 strips "> " from both quoted lines and joins them with <br/> inside one <blockquote>. Paragraph 3 wraps legacy v1 in <del>...</del>.

Example 2

text = (
    "Check latency < 50ms & retries\n"
    "> alert on-call\n"
    "Resume ~~canary\n\n"
    "next ~~step~~"
)
markdown_to_html(text)

Output:

<p>Check latency &lt; 50ms &amp; retries</p>
<blockquote>alert on-call</blockquote>
<p>Resume ~~canary</p>
<p>next <del>step</del></p>

Walk-through: Paragraph 1 alternates plain, quoted, and plain lines, producing <p>, <blockquote>, and <p> in order while escaping < and &. The "~~" before "canary" has no closing partner inside its <p> block (it cannot pair across "\n\n"), so "~~canary" stays literal, whereas "~~step~~" in Paragraph 2 becomes <del>step</del>.

Constraints

  • 0 <= len(text) <= 10^5 characters; input may use Unix ("\n") or Windows ("\r\n") newlines.
  • Time and space complexity must both be O(n) where n = len(text).
  • Standard library only (html is allowed).

Step-by-step walkthrough

  1. Clarify the Markdown subset and HTML validity rules

    We want to implement markdown_to_html(text: str) -> str for four features: paragraphs (<p>), soft line breaks (<br/>), blockquotes (<blockquote>), and strikethrough (<del>). Before writing code, state how every boundary case behaves so the parser is completely unambiguous:

    • Blank lines and empty paragraphs: two or more consecutive newlines ("\n\n") — or lines containing only spaces and tabs — separate paragraphs. Leading, trailing, or repeated blank lines ("\n\n\n\n") act as a single separator and never emit empty <p></p> tags. Empty input returns "".
    • Leading and trailing spaces on a line: stripped from each line's content so "first \n second" renders cleanly as <p>first<br/>second</p>.
    • Quote marker: only a line whose very first two characters are "> " (greater-than followed immediately by a space) is quoted. ">nospace" and " > indented" are ordinary text.
    • Mixed plain and quoted lines in one paragraph: in HTML, <p> cannot contain <blockquote> (browsers forcefully close <p> when <blockquote> starts). When a paragraph mixes plain and quoted lines without a blank line between them, each consecutive run of plain lines becomes a <p>...</p> and each consecutive run of quoted lines becomes a <blockquote>...</blockquote>, in order.
    • Valid HTML (entity escaping): raw &, <, and > inside user text must undergo HTML entity escaping (replacing special characters with safe codes &amp;, &lt;, and &gt;) so input like a < b never opens a broken HTML tag.
    Input:   "Hi\nthere\n\n> quoted\n\n~~old~~ & new"
    
    Output:  <p>Hi<br/>there</p>
             <blockquote>quoted</blockquote>
             <p><del>old</del> &amp; new</p>
    
  2. Choose the scan strategy: block passes first, inline pass second

    Notice that our grammar operates at two distinct levels:

    1. Block level (<p> vs. <blockquote>): determined purely line by line (is this line blank, does it start with "> ", or is it plain text?).
    2. Inline level (~~...~~, escaping, <br/>): determined character by character inside a single block.

    Strikethrough requires lookahead — peeking ahead in the text before deciding how to format the current token — because when we see an opening ~~, we cannot output <del> until we confirm a matching ~~ exists before the current block ends!

    Splitting the input into blocks first makes inline lookahead trivial: each block's text is passed on its own to render_inline, so ~~ can never cross a paragraph or blockquote boundary. Touching the input in three small linear passes (split lines -> group blocks -> scan inline) still examines each of the n characters a constant number of times, running in O(n) time and O(n) space while avoiding a brittle single-pass state machine with backtrack buffers.

  3. Phase 1: Normalize newlines and split into paragraphs

    First replace Windows "\r\n" line endings with "\n" and split on "\n". Walk the lines with an accumulator list current_paragraph:

    • Non-blank lines append to current_paragraph.
    • A blank line (line.strip() == "") closes current_paragraph only if it is non-empty. That single if current_paragraph: guard automatically ignores leading blank lines, trailing newlines (like "Hello\n"), and runs of 3+ newlines.
    raw_lines:  ["", "Hello", "world", "", "   ", "> quote", ""]
                   skip  └──── paragraph 1 ────┘  skip skip  └─ para 2 ─┘ skip
    paragraphs: [["Hello", "world"], ["> quote"]]
    
    from typing import List
    
    
    def split_paragraphs(lines: List[str]) -> List[List[str]]:
        """Group consecutive non-blank lines into paragraphs."""
        paragraphs: List[List[str]] = []
        current_paragraph: List[str] = []
    
        for line in lines:
            if line.strip() == "":
                if current_paragraph:
                    paragraphs.append(current_paragraph)
                    current_paragraph = []
            else:
                current_paragraph.append(line)
    
        if current_paragraph:
            paragraphs.append(current_paragraph)
        return paragraphs
    
  4. Phase 2: Split each paragraph into plain and blockquote runs

    Within one paragraph, walk line by line and group adjacent lines that share the same is_quote flag (True for quoted, False for plain).

    One subtle ordering trap: always check line.startswith("> ") before calling .strip()! If a line is literally "> " (an empty quoted line), calling .strip() first turns it into ">", deleting the trailing space and misclassifying it as plain text.

    paragraph: ["Intro", "> quoted 1", "> quoted 2", "Outro"]
                 plain     quote         quote         plain
    groups:    [(False, ["Intro"]), (True, ["quoted 1", "quoted 2"]), (False, ["Outro"])]
    

    And if two blockquote runs were separated by a blank line in the original document ("> a\n\n> b"), split_paragraphs already placed them in separate paragraphs, so they naturally emit two separate <blockquote> elements (since a blank line always closes an active quote block).

    from typing import List, Tuple
    
    
    def group_lines(paragraph: List[str]) -> List[Tuple[bool, List[str]]]:
        """Split one paragraph into consecutive runs of quoted ("> ") vs. plain lines."""
        groups: List[Tuple[bool, List[str]]] = []
    
        for line in paragraph:
            # Check "> " BEFORE stripping: stripping "> " first turns it into ">" and loses the space!
            is_quote = line.startswith("> ")
            if is_quote:
                cleaned_line = line[2:].strip()
            else:
                cleaned_line = line.strip()
    
            if groups and groups[-1][0] == is_quote:
                groups[-1][1].append(cleaned_line)
            else:
                groups.append((is_quote, [cleaned_line]))
    
        return groups
    
  5. Phase 3: Render inline strikethrough, escape HTML, and add `<br/>`

    For each (is_quote, cleaned_lines) group, join cleaned_lines with "\n" so a strikethrough like "~~line 1\nline 2~~" can span a soft line break inside the same block, while never crossing into another block.

    To pair ~~ markers in O(n) time, maintain an integer index cursor = 0 and call text.find("~~", cursor):

    1. Search for an opener open_pos = text.find("~~", cursor). If -1, no ~~ remains; break.
    2. Search for its closer close_pos = text.find("~~", open_pos + 2). If -1, no other ~~ exists anywhere later in this block, so open_pos is unmatched and everything from cursor to the end is plain text; break!
    3. Otherwise, escape text[cursor:open_pos], wrap escaped text[open_pos + 2:close_pos] in <del>...</del>, and advance cursor = close_pos + 2.

    Inside escape_text, escape &, <, > before replacing "\n" with "<br/>". Reversing those two steps would escape the < and > of your own <br/> tags into &lt;br/&gt;!

    from typing import List
    
    import html
    
    
    def render_inline(text: str) -> str:
        """Render ~~strikethrough~~, escape HTML special characters, and convert soft newlines to <br/>."""
        rendered_pieces: List[str] = []
        cursor = 0
    
        while True:
            open_pos = text.find("~~", cursor)
            if open_pos == -1:
                break
    
            close_pos = text.find("~~", open_pos + 2)
            if close_pos == -1:
                break
    
            before_strike = escape_text(text[cursor:open_pos])
            inside_strike = escape_text(text[open_pos + 2:close_pos])
            rendered_pieces.append(before_strike)
            rendered_pieces.append("<del>" + inside_strike + "</del>")
            cursor = close_pos + 2
    
        rendered_pieces.append(escape_text(text[cursor:]))
        return "".join(rendered_pieces)
    
    
    def escape_text(text: str) -> str:
        """Escape &, <, and > first, then turn single newlines into <br/> tags."""
        escaped = html.escape(text, quote=False)
        return escaped.replace("\n", "<br/>")
    
  6. Trace the full example end to end

    Walk through Example 1:

    Input string:
      "Deploy window opens at 09:00\n  and closes at 10:30.\n\n> Freeze main branch\n> monitor error rates\n\nRoll back ~~legacy v1~~ traffic."
    
    1. split_paragraphs:
       - Paragraph 1: ["Deploy window opens at 09:00", "  and closes at 10:30."]
       - Paragraph 2: ["> Freeze main branch", "> monitor error rates"]
       - Paragraph 3: ["Roll back ~~legacy v1~~ traffic."]
    
    2. group_lines + render_inline:
       - Paragraph 1 -> [(False, ["Deploy window opens at 09:00", "and closes at 10:30."])]
                     -> "<p>Deploy window opens at 09:00<br/>and closes at 10:30.</p>"
       - Paragraph 2 -> [(True, ["Freeze main branch", "monitor error rates"])]
                     -> "<blockquote>Freeze main branch<br/>monitor error rates</blockquote>"
       - Paragraph 3 -> [(False, ["Roll back ~~legacy v1~~ traffic."])]
                     -> open_pos=10, close_pos=21 -> "<p>Roll back <del>legacy v1</del> traffic.</p>"
    

    Check a handful of tricky edge cases against the exact same rules: - "~~x~~ and ~~y" -> <p><del>x</del> and ~~y</p> (first pair matches; second opener has close_pos == -1 and stays literal). - "~~open\n\nclose~~" -> <p>~~open</p>\n<p>close~~</p> (split into separate blocks before render_inline runs). - "> a\n> b\n\n> c" -> <blockquote>a<br/>b</blockquote>\n<blockquote>c</blockquote> (blank line separates quote groups).

  7. Complete solution

    from typing import List, Tuple
    
    import html
    
    
    def markdown_to_html(text: str) -> str:
        """Convert a small Markdown subset to valid HTML."""
        # Phase 1: normalize Windows "\r\n" line endings so every line break is "\n".
        normalized_text = text.replace("\r\n", "\n")
        raw_lines = normalized_text.split("\n")
    
        # html_blocks: top-level "<p>...</p>" and "<blockquote>...</blockquote>" strings in document order
        html_blocks: List[str] = []
    
        # Phase 2 & 3: split into paragraphs at blank lines, then split mixed paragraphs into plain/quote runs.
        paragraphs = split_paragraphs(raw_lines)
        for paragraph_lines in paragraphs:
            block_runs = group_lines(paragraph_lines)
            for is_quote, cleaned_lines in block_runs:
                # Join lines inside one block with "\n" so strikethrough can span soft breaks within the block.
                block_text = "\n".join(cleaned_lines)
                rendered_inner = render_inline(block_text)
                if is_quote:
                    html_blocks.append("<blockquote>" + rendered_inner + "</blockquote>")
                else:
                    html_blocks.append("<p>" + rendered_inner + "</p>")
    
        return "\n".join(html_blocks)
    
    
    def split_paragraphs(lines: List[str]) -> List[List[str]]:
        """Group consecutive non-blank lines into paragraphs.
    
        Returns a list of paragraphs, e.g. [["line 1", "line 2"], ["> quote"]].
        """
        paragraphs: List[List[str]] = []
        # current_paragraph: non-blank lines accumulated since the last blank line
        current_paragraph: List[str] = []
    
        for line in lines:
            # Whitespace-only lines act as blank separators just like completely empty lines.
            if line.strip() == "":
                # Only flush when current_paragraph is non-empty so repeated blank lines never create "<p></p>".
                if current_paragraph:
                    paragraphs.append(current_paragraph)
                    current_paragraph = []
            else:
                current_paragraph.append(line)
    
        # Flush the final paragraph if the input did not end with a blank line.
        if current_paragraph:
            paragraphs.append(current_paragraph)
        return paragraphs
    
    
    def group_lines(paragraph: List[str]) -> List[Tuple[bool, List[str]]]:
        """Split one paragraph into consecutive runs of quoted ("> ") vs. plain lines.
    
        Returns [(is_quote, cleaned_lines)], e.g. [(False, ["Intro"]), (True, ["q1", "q2"])].
        """
        groups: List[Tuple[bool, List[str]]] = []
    
        for line in paragraph:
            # Check "> " BEFORE stripping: stripping "> " first turns it into ">" and loses the space!
            is_quote = line.startswith("> ")
            if is_quote:
                cleaned_line = line[2:].strip()
            else:
                cleaned_line = line.strip()
    
            # Merge adjacent lines of the same kind into a single <p> or <blockquote> block.
            if groups and groups[-1][0] == is_quote:
                groups[-1][1].append(cleaned_line)
            else:
                groups.append((is_quote, [cleaned_line]))
    
        return groups
    
    
    def render_inline(text: str) -> str:
        """Render ~~strikethrough~~, escape HTML special characters, and convert soft newlines to <br/>."""
        # rendered_pieces: HTML fragments built left-to-right across this single block
        rendered_pieces: List[str] = []
        cursor = 0
    
        while True:
            # Pass `cursor` to str.find instead of slicing text[cursor:] so scanning stays O(n), not O(n^2).
            open_pos = text.find("~~", cursor)
            if open_pos == -1:
                break
    
            close_pos = text.find("~~", open_pos + 2)
            if close_pos == -1:
                # No closing "~~" exists anywhere after open_pos in this block, so the rest is literal text.
                break
    
            before_strike = escape_text(text[cursor:open_pos])
            inside_strike = escape_text(text[open_pos + 2:close_pos])
            rendered_pieces.append(before_strike)
            rendered_pieces.append("<del>" + inside_strike + "</del>")
            cursor = close_pos + 2
    
        # Escape whatever plain text (including any unmatched "~~") remains after the last matched pair.
        rendered_pieces.append(escape_text(text[cursor:]))
        return "".join(rendered_pieces)
    
    
    def escape_text(text: str) -> str:
        """Escape &, <, and > first, then turn single newlines into <br/> tags."""
        # Escape BEFORE inserting "<br/>", otherwise "<br/>" itself would turn into "&lt;br/&gt;".
        escaped = html.escape(text, quote=False)
        return escaped.replace("\n", "<br/>")
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine laying out a newspaper page in two distinct passes: first, a layout editor slices the raw manuscript at blank lines into separate rectangular boxes (<p> paragraphs and <blockquote> callouts); second, a copy editor works inside one box at a time, pairing up ~~...~~ strikethrough markers, escaping special symbols, and turning single line wraps into <br/>. Because the copy editor only ever sees one isolated box, inline formatting can never accidentally cross from one paragraph or blockquote into another.

Why do naive one-step approaches fail here? Running a global regular expression like ~~(.*?)~~ across the entire string pairs an unmatched ~~ in Paragraph 1 with an unrelated ~~ in Paragraph 4, breaking the rule that formatting never crosses paragraphs. Conversely, scanning character by character and immediately outputting <del> the instant you see ~~ fails whenever no closing ~~ appears later in the paragraph, leaving an unclosed <del> tag and invalid HTML.

Trace "a < b\n> quote\n\n~~cut~~" step by step: 1. Paragraph split: the blank line (\n\n) splits the lines into ["a < b", "> quote"] and ["~~cut~~"]. 2. Block grouping: the first paragraph mixes plain and quoted lines, so group_lines splits it into [(False, ["a < b"]), (True, ["quote"])]; the second becomes [(False, ["~~cut~~"])]. 3. Inline rendering: "a < b" escapes < to &lt; -> <p>a &lt; b</p>; "quote" becomes <blockquote>quote</blockquote>; "~~cut~~" matches open_pos = 0, close_pos = 5 -> <p><del>cut</del></p>.

Complexity

  • Time: O(n), where n is the number of characters in text. Each pass touches every character a small constant number of times: normalizing "\r\n" and splitting on "\n" scans text once; split_paragraphs and group_lines inspect and strip each line once; inside render_inline, text.find("~~", cursor) advances cursor strictly forward without rescanning earlier characters; and html.escape plus "\n".join(...) scan the text once more (expanding characters by at most a constant factor, such as 1 character & -> 5 characters &amp;, or "\n" -> "<br/>").
  • Space: O(n). Storing the split lines, grouped block strings, and final HTML output each takes memory proportional to the input length n.

Edge cases

  • Empty or whitespace-only input ("", "\n\n\n", " \t\n "): split_paragraphs produces [], returning "" with zero <p></p> tags.
  • Single trailing newline ("Hello\n"): splits into ["Hello", ""]; the trailing "" is treated as a blank separator, producing <p>Hello</p> without a trailing <br/>.
  • Three or more consecutive newlines ("a\n\n\n\nb"): if current_paragraph: flushes "a" on the first blank line and ignores the remaining blank lines, yielding <p>a</p>\n<p>b</p>.
  • Quote marker edge cases ("> ", ">nospace", " > x"): "> " with nothing after it stays a valid quote (<blockquote></blockquote>), whereas ">nospace" and " > x" lack a leading "> " and render as plain text with &gt;.
  • Consecutive blockquotes separated by blank lines ("> a\n\n> b"): land in separate paragraphs and render as two separate <blockquote> elements.
  • Mixed plain and quoted lines ("Intro\n> q1\n> q2\nOutro"): split cleanly into <p>Intro</p>, <blockquote>q1<br/>q2</blockquote>, <p>Outro</p> so <blockquote> is never nested illegally inside <p>.
  • Unmatched, odd, or adjacent tildes ("~~a", "a ~ b", "~~~a~~", "~~~~"): lone ~ and unmatched ~~ remain literal text; "~~~~" produces <del></del>; "~~~a~~" opens at index 0 and closes at index 3 to give <del>~a</del>.
  • Strikethrough across boundaries: "~~one\ntwo~~" spans a soft break inside one block (<del>one<br/>two</del>), whereas "~~one\n\ntwo~~" and "~~one\n> two~~" cross block boundaries and stay literal ~~.
  • Raw HTML characters ("<script>&</script>", "~~<b>~~"): HTML entity escaping (converting &, <, > to &amp;, &lt;, &gt;) turns raw tags into safe visible text both outside and inside <del>.

Common mistakes

  • Nesting <blockquote> inside <p>. In the HTML specification, <p> cannot contain block-level elements like <blockquote>; an HTML parser auto-closes <p> early and leaves a stray unmatched </p> at the end.
  • Splitting paragraphs with text.split("\n\n"). On "a\n\n\nb", .split("\n\n") yields ["a", "\nb"], leaving a leading newline on "b" that turns into a bogus <p><br/>b</p>, and it fails completely when a blank line contains spaces ("a\n \nb").
  • Calling line.strip() before line.startswith("> "). A blank quoted line "> " strips down to ">", losing its space and turning into literal &gt; instead of a blockquote line.
  • Escaping HTML after inserting <br/> or <del>. Calling html.escape last turns your own tags into literal &lt;br/&gt; and &lt;del&gt;.
  • Slicing strings inside the ~~ loop (text[cursor:].find("~~")). Every slice copies up to O(n) characters, turning "~~a~~~~a~~..." with O(n) pairs into O(n^2) time; always pass the start index text.find("~~", cursor).

Alternative approaches

  • Per-block non-greedy regex: once a single block's text is HTML-escaped (which leaves ~ untouched), re.sub(r"~~(.*?)~~", r"<del>\1</del>", escaped, flags=re.DOTALL) pairs ~~ identically to the find loop in O(n) time, though explicit index scanning is easier to extend when adding nested markers like **bold**.
  • Single-pass character state machine: scan characters once while maintaining line-start state and a tentative buffer after seeing an opening ~~; flush the buffer inside <del>...</del> if a closing ~~ arrives before a block boundary, or flush "~~" + buffer literally when the block ends. Same O(n) complexity, with significantly more state transitions to debug.

Follow-up questions

  • How would you support nested inline markers (such as bold alongside strikethrough) without emitting mis-nested HTML tags? Replace the two find calls in render_inline with a delimiter stack (a last-in, first-out list recording each unmatched opening marker ~~ or ** and its position in the output buffer). When a closing marker arrives, if it matches the top of the stack, wrap the slice since that opener in <del> or <strong> and pop; if an earlier opener of that type sits deeper in the stack, pop and demote any intervening unmatched openers above it to literal text first so HTML tags always close in strict inside-out order. Each marker is pushed and popped at most once, keeping the inline pass O(n).
  • How could you convert a multi-gigabyte Markdown stream without loading the entire document into memory? Stream the input file line by line (for line in file_handle:) instead of reading the full string into memory. Because neither blockquotes nor inline ~~ formatting can ever cross a blank line, you only need to buffer current_paragraph up to the next blank line, render its HTML blocks, flush them to the output stream, and clear current_paragraph, dropping peak memory from O(n) to O(L) where L is the length of the single longest paragraph.
  • Beyond hand-written examples, how would you systematically verify HTML validity and text preservation? Combine targeted boundary unit tests with property-based fuzz testing (generating hundreds of random strings built from tricky tokens like "~", "~~", ">", "> ", "\n", "\n\n", "<", "&"). Feed every output into a strict HTMLParser validator to assert two invariants automatically: (1) every opened tag closes in valid nesting order with zero stray text outside blocks, and (2) stripping tags, whitespace, ~, and leading "> " prefixes recovers the exact sequence of visible input characters without dropping or duplicating anything.

Follow-up questions

Similar questions

More Samsara interview questions

All 4 Samsara questions →